用 C++ 統計給定數字時鐘顯示相同數字的次數
假設我們有一個 HH:MM 型別的數字時鐘,它只顯示小時和分鐘。我們得到小時和分鐘作為輸入。目標是計算所有數字都相同(H=M)的次數。
這種情況一天發生 3 次,第一次在午夜 00:00,然後是 11:11,最後是 22:22。時間採用 24 小時製表示。
輸入
Input: 12 hours 22 minutes.
輸出
2
說明 − 對於 00:00 和 11:11。12 小時內出現兩次。
輸入
Input: 48 hours 22 minutes.
輸出
5
說明 − 對於 00:00、11:11 和 22:22。
下面程式中使用的步驟如下
- 變數 hours 和 minutes 儲存輸入。
- 函式 countIdentical(int hours, int minutes) 獲取分鐘和小時並返回 HH:MM 數字都相同的次數。
- 對於 00:00,將計數初始化為 1。
- 對於每個小時為 11 和 22,以及分鐘為 11 和 22,計數加 1。
- 迴圈結束後返回結果。
- Count 是期望的結果。
- 列印計數。
示例
// 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;
}輸出
Times when all digits are identical in HH:MM : 6
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP