C++ 中統計整數中孔洞的數量


給定一個包含數字 0 到 9 中孔洞數量的陣列 holes[10]。目標是找到給定輸入整數的孔洞數量。已知 - holes[] = { 2, 1, 1, 0, 0, 1, 1, 1, 0 }

例如

輸入

number = 239143

輸出

Count the number of holes in an integer are: 3

解釋

We will count holes given in holes[]
239143 ( 1+0+0+2+0+0 )

輸入

number = 12345

輸出

Count the number of holes in an integer are: 3

解釋

We will count holes given in holes[]
12345 ( 1+1+0+0+1)

以下程式中使用的方案如下

只需使用 num%10 獲取每個最左邊的數字,並將 holes[num%10] 中的孔洞計數新增到 count 中。然後將數字 num 減去 10。

  • 輸入一個整數。

  • 初始化 holes[] 陣列。

  • 函式 holes_integer(int number, int holes[]) 返回整數中孔洞數量的計數。

  • 將初始計數設定為 0。

  • 遍歷直到 number > 0。

  • 將最左邊的數字作為 temp = number % 10。將 holes[temp] 新增到 count 中。

  • 將數字減少 10。

  • 最後返回 count 作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int holes_integer(int number, int holes[]){
   int count = 0;
   while (number > 0){
      int temp = number % 10;
      count = count + holes[temp];
      number = number/10;
   }
   return count;
}
int main(){
   int number = 239143;
   int holes[] = { 2, 1, 1, 0, 0, 1, 1, 1, 0};
   cout<<"Count the number of holes in an integer are: "<<holes_integer(number, holes);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Count the number of holes in an integer are: 2

更新於:2021年1月5日

447 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告