Next Palindromic Time
National Olympiad — National round (2011 season)
Submission name: ptime.cpp
Problem summary
Find the first strictly later clock time whose four digits HHMM form a palindrome. The clock wraps after 23:59.
Input
A valid time HH:MM.
Output
The next palindromic time, in HH:MM format.
Constraints
00 ≤ HH ≤ 23; 00 ≤ MM ≤ 59.
Worked example
An independently prepared example for this explanation.
Input
00:00
Output
01:10
Solution analysis
- Convert the time to minutes since midnight. Advance by one minute before testing, because even an already palindromic time must wait.
- For each candidate, recover hour and minute. Test hour/10 == minute%10 and hour%10 == minute/10. Reduce time modulo 1440.
- Starting at 00:00, the next match is 01:10. Starting at 23:59 wraps to 00:00.
Why it works
The loop examines times in chronological order starting strictly after the input. Its first accepted candidate satisfies both mirrored digit equalities and is therefore exactly the earliest valid answer.
Watch out. Do not return the input itself. Preserve leading zeroes.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int hour, minute;
char colon;
cin >> hour >> colon >> minute;
int time = hour * 60 + minute;
// Advance before testing: the required time is strictly later.
do {
time = (time + 1) % 1440;
hour = time / 60;
minute = time % 60;
} while (hour / 10 != minute % 10 || hour % 10 != minute / 10);
cout << setfill('0') << setw(2) << hour << ':' << setw(2) << minute << '\n';
}