The challenge
Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation.
Examples
"1999" --> "20th" "2011" --> "21st" "2154" --> "22nd" "2259" --> "23rd" "1124" --> "12th" "2000" --> "20th"
The solution in Java code
Option 1:
public class Solution{ public static String whatCentury(int year) { int century = (year + 99) / 100; if (century / 10 == 1) return century + "th"; switch(century % 10) { case 1: return century + "st"; case 2: return century + "nd"; case 3: return century + "rd"; default: return century + "th"; } } }
Option 2:
public class Solution{ public static String whatCentury(int year) { int c = (int)Math.ceil(year/100.), a = c%100, b = c%10; return c + (10 < a && a < 14 ? "th" : b == 1 ? "st" : b == 2 ? "nd" : b == 3 ? "rd" : "th"); } }
Option 3:
public class Solution{ public static String whatCentury(int year) { int century = year < 100 ? 1 : year % 100 == 0 ? year / 100 : year / 100 + 1; String postfix = "th"; if (century < 11 || century > 20) { switch (century % 10) { case 1: postfix = "st"; break; case 2: postfix = "nd"; break; case 3: postfix = "rd"; break; } } return century + postfix; } }
Test cases to validate our solution
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomething() { assertEquals("20th", Solution.whatCentury(1999)); assertEquals("21st", Solution.whatCentury(2011)); assertEquals("22nd", Solution.whatCentury(2154)); assertEquals("23rd", Solution.whatCentury(2259)); } }