We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
A solution with many comments explaining the logic behind the code.
Does not use any Java Libraries like Date, Calendars, or SimpleDataFormat
Can set the day of the year to find besides 256, which increases code re-usability.
importjava.io.*;importjava.util.*;importjava.text.*;importjava.math.*;importjava.util.regex.*;publicclassSolution{staticStringsolve(intyear){//Change this to find any day of the year. intdayToFind=256;//Store days of month in a collection we can use for calculations laterint[]daysInMonths={31,28,31,30,31,30,31,31,30,31,30,31};//If year is greater then 1918, lets use gregorian calendarif(year>1918){// Gregorian: Is leap year if divisible by 400, or divisible by 4 but not 100if((year%400==0)||(year%4==0&&year%100!=0)){daysInMonths[1]=29;}}elseif(year<=1917){//Use Julian calendar instead//Julian: Is leap year if divisible by 4if(year%4==0){daysInMonths[1]=29;}}else{//is 1918, do special case for the switch in calendars from Julian to Gregorian//Feb started on day 14, meaning there were 29 - 14 = 15 days in this month for this yeardaysInMonths[1]=15;}//keep memory of the sum of the days in each month intrunningTotal=0;//keep memory of which month we are in, not 0 indexingintcurrentMonth=0;/*Loop through the months, and sum the days for each, checking if we exceeded the day we are trying to find. If we did, we know that day is in the current month. Then we just do some subtractions to get the actual day */for(inti=0;i<13;i++){//Add the running total with this current monthrunningTotal+=daysInMonths[i];currentMonth+=1;//If we exceeded the day count, we know its in this month so break.if(runningTotal>dayToFind){break;}}//Now lets subtract to get the result, with an offset of 1intdayOfMonth=(daysInMonths[currentMonth]-(runningTotal-dayToFind))-1;//Format Day and monthStringday=(dayOfMonth<10)?"0"+dayOfMonth:""+dayOfMonth;Stringmonth=(currentMonth<10)?"0"+currentMonth:""+currentMonth;returnday+"."+month+"."+year;}publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intyear=in.nextInt();Stringresult=solve(year);System.out.println(result);}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day of the Programmer
You are viewing a single comment's thread. Return to all comments →
A solution with many comments explaining the logic behind the code.
Does not use any Java Libraries like Date, Calendars, or SimpleDataFormat
Can set the day of the year to find besides 256, which increases code re-usability.