สมมติว่ามีนาฬิกาดิจิทัลแบบ HH:MM แสดงเวลาเป็นชั่วโมงและนาทีเท่านั้น เราได้รับจำนวนชั่วโมงและนาทีเป็นอินพุต เป้าหมายคือนับจำนวนครั้งที่ตัวเลขทั้งหมดเหมือนกัน (H = M)
เหตุการณ์นี้เกิดขึ้น 3 ครั้งต่อวัน: 00:00 ตอนเที่ยงคืน, 11:11 และ 22:22 เนื่องจากใช้รูปแบบ 24 ชั่วโมง
อินพุต
Input: 12 hours 22 minutes.
เอาต์พุต
2
คำอธิบาย − เวลา 00:00 และ 11:11 เกิดขึ้น 2 ครั้งใน 12 ชั่วโมง
อินพุต
Input: 48 hours 22 minutes.
เอาต์พุต
5
คำอธิบาย − เวลา 00:00, 11:11, 22:22
วิธีการที่ใช้ในโปรแกรมด้านล่าง
- ตัวแปร hours และ minutes เก็บค่าอินพุต
- ฟังก์ชัน countIdentical(int hours, int minutes) คืนค่าจำนวนครั้งที่ตัวเลข HH:MM เหมือนกันทั้งหมด
- เริ่มต้น count = 1 สำหรับ 00:00
- ลูปสำหรับชั่วโมง 11 และ 22 และนาที 11 และ 22 เพิ่ม count
- คืนค่าผลลัพธ์
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
int countIdentical(int hours, int minutes) {
int count = 1; // 00:00
for (int i = 0; i <= 99 && i < hours; i += 11) {
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;
}
ผลลัพธ์
Times when all digits are identical in HH:MM : 6