Hackerrank day of the programmer solution

Farzin Pashaee
2 min readMar 10, 2022

--

In this article, you can find the solution for the Hackerrank day of the programmer challenge using Java programming language. but let's start with what this challenge is all about. according to the challenge description:

“From 1700 to 1917, Russia’s official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that in 1918, February 14th was the 32nd day of the year in Russia.”

Now considering this background information the assignment is to write the code which by getting a year as input can find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is the year.

Based on the given information we have 3 situations that we need to deal with. Before and after 1918 and 1918 itself as an exceptional condition. Following the rules to find the date for the programmers using the Julian and the Gregorian calendar approach, we will find out the key difference is the way they calculate the leap year.

  • 1918: as an exception will return “26.09.1918”
  • Before 1918: The Julian leap years are divisible by 4.
  • After 1918: Using the Gregorian calendar approach leap years are divisible by 4 with an extra condition for the years that are divisible to 100 must be divisible to 400 too in order to consider leap.

In the code, after checking if the year meets the requirements we will change the number of days in the array for February from 28 to 29.

public static String dayOfProgrammer(int year) {

int[] dayofMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
int dayOfYear = 256, totalCount = 0, dayOfMonth = 1, month = 1;

if( year == 1918 ) return "26.09.1918";
if( year >= 1919 ) { // after 1918
if (year % 4 == 0)
if (year % 100 == 0) {
if (year % 400 == 0) dayofMonth[1] = 29;
} else {
dayofMonth[1] = 29;
}
} else { // before 1918
if (year % 4 == 0)
dayofMonth[1] = 29;
}
// Caclculate the day of the month
for( int i = 0 ; i < 12 ; i++ ){
month = i+1;
if( dayofMonth[i] + totalCount >= dayOfYear){
dayOfMonth = dayOfYear - totalCount;
break;
}
totalCount += dayofMonth[i];
}
return String.format("%02d" , dayOfMonth) + "." + String.format("%02d" , month) + "." + year;
}

Examples to test the code:

dayOfProgrammer(1918); // 26.09.1918
dayOfProgrammer(2016); // Leap year - 12.09.2016
dayOfProgrammer(1987); // Common year - 13.09.1987

The above code will pass all the tests in The Hackerrank.

--

--

Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic