Data Structures & Algorithms: centuryfromYear

Niani Byrd
2 min readOct 9, 2021

Let’s take a look at another common DSA question:

Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second — from the year 101 up to and including the year 200, etc.

There are several ways to solve this challenge, but we’ll take a look at two distinct solutions. The first is the easiest, but the least efficient. The second solution will be a little harder, but far more efficient.

First we create a function called centuryFromYear and give it an argument of year. We’ll define a variable called centuryCount and set it equal to zero.

function centuryFromYear(year) {
let centuryCount = 0
}

We know that a year will have to be greater than 0 and that a century is 100 years. We’ll increment our century count by one each time we define a new year. Afterwards, we return the centuryCount to arrive at the correct answer.

function centuryFromYear(year) {
let centuryCount = 0
while (year > 0){
year = year - 100
centuryCount = centuryCount + 1
}
return centuryCount
}

Believe it or not, there’s a better way to reach the correct answer and we can accomplish it all on one line! Have you ever heard of Math.ceil in JavaScript? This function will always round a number up to the next largest integer. So, for example:

console.log(Math.ceil(.57))
// expected output: 1
console.log(Math.ceil(26.1))
// expected output: 27
console.log(Math.ceil(-8.009))
// expected output: -8

In regards to this question, we can use the Math.ceil function to return the century year because it will automatically take care of finding the next largest integer for us. Lastly, we pass in the year divided by 100 and we have our answer!

function centuryFromYear(year) {
return Math.ceil(year/100)
}

Thanks for reading and Happy Coding!

--

--