Its Sunday and it is time for CodeForces. Today I have taken a look at round number 816, Problem A.
The problem initially looks rather easy and you think that nothing can go wrong, until you do not try it. Then you see the wrong answers…
In general, we have hours and minutes and we have to calculate the minutes left to the next palindrome. E.g., if we have as an input 15:50, we give 1 as an answer, because the next minute we would have 15:51, and this is a palindrome.
The problem is well described here.
Question: What can go wrong, knowing that there is a TimeSpan class in .NET, which is actually perfect for time issues?
Answer: Two things. In general, if you simply forget, that you should cast to string and “05” is translated to “5” as an integer and then 5:50 is not a palindrome any more, then you are in a bit of a trouble. However, if you take care of this small issue, then everything is perfect. I managed to do it rather quickly, probably less than 15 minutes, but I admit, that I had to take a look at the failing tests.
Pretty much, that’s all here comes the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Startup { static void Main() { List<int> liTime = Console.ReadLine().Split(':').Select(int.Parse).ToList(); int iHour = liTime[0]; int iMin = liTime[1]; int iCounter = 0; string strHour = AddZero(iHour); string strMin = AddZero(iMin); TimeSpan tsCheck; while(ReverseString(strHour)!=strMin) { iCounter++; iMin++; tsCheck= new TimeSpan(iHour, iMin, 0); iHour = tsCheck.Hours; iMin = tsCheck.Minutes; strHour = AddZero(iHour); strMin = AddZero(iMin); } Console.WriteLine(iCounter); } public static string ReverseString(string s) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } public static string AddZero(int iVal) { string strResult; strResult = iVal.ToString(); if (iVal<=9) { strResult = 0 + strResult; } return strResult; } } |
That’s all! 🙂