Software Engineering

# Century From Year in Java

## The challenge#

The first century spans from the year 1 up to and including the year 100The second – from the year 101 up to and including the year 200, etc.

Given a year, return the century it is in.

### Input, Output Examples#

``````centuryFromYear(1705)  returns (18)
centuryFromYear(1900)  returns (19)
centuryFromYear(1601)  returns (17)
centuryFromYear(2000)  returns (20)
``````

## The solution in Java code#

Option 1:

``````public class Solution {
public static int century(int number) {
return (number + 99) / 100;
}
}
``````

Option 2:

``````import java.lang.Math;

public class Solution {
public static int century(int number) {
return (int)Math.ceil((double)number/100);
}
}
``````

Option 3:

``````public class Solution {
public static int century(int number) {
int yearsInCentury = 100;
return number % yearsInCentury == 0
? number/yearsInCentury
: number/yearsInCentury + 1;
}
}
``````

Option 4:

``````public class Solution {
public static int century(int number) {
int century = (int) number / 100;
int remains = (int) number % 100;
if (remains > 0) {
century += 1;
}
return century;

}
}
``````

## Test cases to validate our solution#

``````import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.Random;
public class Tests {
@Test
public void FixedTests() {
assertEquals(18, Solution.century(1705));
assertEquals(19, Solution.century(1900));
assertEquals(17, Solution.century(1601));
assertEquals(20, Solution.century(2000));
assertEquals(1,  Solution.century(89));
}
@Test
public void RandomTests() {
Random rand = new Random();
for(int i = 0; i < 100;) {
int a = rand.nextInt(++i * 100);
int b = (int)(--a/100+1);
assertEquals(b,  Solution.century(++a));
}
}
}
``````