This problem comes straight from Code Signal. 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.
Example
- For
year = 1905, the output should becenturyFromYear(year) = 20; - For
year = 1700, the output should becenturyFromYear(year) = 17.
Input/Output
- [execution time limit] 0.5 seconds (c)
- [input] integer year A positive integer, designating the year. Guaranteed constraints:
1 ≤ year ≤ 2005. - [output] integer
- The number of the century the year is in.
I have a technical interview coming up this week in C, so I have been learning C in my spare time. So for this particular problem we will be using C. If you are familiar with really any programming language C will not be a challenge for you. The only thing you have to get used to is that it is statically typed; meaning, the variables type is determine at compile time and not at run-time like our usual favorites, Python and JavaScript.
If you are a coding newbie, don’t worry, all that means is that you have to declare the variable type in the code. For instance:
//Integers
int five = 5;
//Characters
char firstLetterOfName = I
//"Strings" -> Really just an array of characters
char name[4] = "Isla";
char daughter[5] = {'A','r','y','a','\0'}
There is more to C but that would require a whole new post. In the meantime, let’s get back to our problem at hand.
First, let’s make sure we understand our problem. We need to create a function that takes in an integer and spits out the century it comes from.
Second, let’s plan this out. So how would we usually figure this out? For instance, I was born in 1994. That is in the 20th century. If we divide 1994 by 100 we get 19.94. If we round down to 19 and then add 1 we will get 20. Okay, so that worked for my birth year but what about someone who was born in 2000? That is technically still the 20th century. 2000 divided by 100 is 20. If we add 1 then we get 21. That’s not right. So obviously we have an edge case. This only happens when the year is evenly divisible by 100. So an if statement saying “if the year is evenly divisible by 100 then we just divide and return,” will be needed.
Third, the fun part, execute.
#include <stdio.h>
#include <math.h>
int centuryFromYear(int year){
// If the year is evenly divisible by 100
if(year % 100 == 0){
int div = year/100;
// Divide by 100 and return
return div;
}else{
// Else, divide by 100 and add one
int div = year/100 + 1
// Round down and return
return floor(div);
}
}
Fourth, reflect on your work. Does this compile? Is it optimal? Considering we aren’t doing any looping just an if statement, I would assume this is an O(1) operation.
If you have any feedback or questions, please leave a comment! I love hearing from you.