Count how many times the given digital clock shows identical digits in C++

C++Server Side ProgrammingProgramming

Suppose we have a digital clock of type HH:MM. Which shows the time in hours and minutes only. We are given a number of hours and minutes as input. The goal is to count the number of times all digits are the same. H=M.

This happens 3 times a day, first at 00:00 midnight, then at 11:11 and last at 22:22. As time is represented in 24 hour format.

Input

Input: 12 hours 22 minutes.

Output

2

Explanation − For times 00:00 and 11:11. Twice in 12 hours.

Input

Input: 48 hours 22 minutes.

Output

5

Explanation − For times 00:00 and 11:11, 22:22 .

Approach used in the below program is as follows

• Variables hours and minutes store the input.
• Function countIdentical(int hours, int minutes) takes minutes and hours and return count of no. of times all HH;MM digits are the same.
• For 00:00 initialize count as 1.
• For each hour as 11 and 22 and minutes as 11 and 22 increment count by 1.
• Return the result after the loop ends.
• Count is the desired result.
• Print the count.

Example

Live Demo

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// examples- 11:11 11hrs 11 mins, 22:22
int countIdentical(int hours, int minutes){
// Initialized to 1 because of 00:00
int i, count=1;
// For double digit hours
for (i = 0; i <= 99 && i < hours; i = i + 11) {
// Double digit minutes
if ((i % 10) < minutes)
count++;
}
return count;
}
int main(){
int hours = 48;
int minutes = 22;
cout <<"Times when all digits are identical in HH:MM :"
<< countIdentical(hours, minutes);
return 0;
}

Output

Times when all digits are identical in HH:MM : 6