C++中範圍內的單一數字計數


給定兩個數字start和end代表一個範圍。目標是找到[start, end]之間存在的單一數字的個數。

我們可以透過以下步驟檢查數字是否為單一數字:如果我們取一個數字13,那麼1² + 3² = 10,然後1² + 0² = 1,所以最終的和是1,所以13是單一數字。

例如

輸入

start=1 end=20

輸出

Count of Unary Numbers in a Range are: 5

解釋

The numbers are :
1, 7, 10, 12, and 13

輸入

start=50 end=100

輸出

Count of Unary Numbers in a Range are: 7

解釋

The numbers are −
59, 63, 67, 74, 75, 78, and 89

下面程式中使用的演算法如下

在1到9之間,數字1和7是單一數字。對於其他數字,我們將使用數字平方和,直到結果為1。對該範圍內的所有數字繼續此過程。以這種方式找到的所有單一數字,計數器加1。

  • 以兩個整數start、end作為輸入。

  • 函式check_unary(int number)如果傳入的值是單一數字則返回true,否則返回false。

  • 函式Unary_range(int start, int end)獲取範圍變數並返回該範圍內單一數字的個數。

  • 將初始計數設定為0。使用for迴圈,從i=start遍歷到end。如果check_unary(i)返回true,則遞增計數。

  • 在check_unary(int number)內部,獲取臨時變數count。

  • 如果數字N為1或7,則返回true。對於所有小於10的其他數字返回false。(number/10 == 0)。

  • 然後在while迴圈中計算數字平方和。

  • 再次對這樣的連續和呼叫check_unary(int number),直到和變為1。

  • 返回count作為結果。

示例

 線上演示

#include <iostream>
using namespace std;
bool check_unary(int number){
   int total;
   if (number == 1 ){
      return true;
   }
   else if(number == 7){
      return true;
   }
   else if (number / 10 == 0){
      return false;
   }
   while (number!= 0){
      int temp = number % 10;
      total = total + temp * temp;
      number = number / 10;
   }
   check_unary(total);
}
int Unary_range(int start, int end){
   int count = 0;
   for (int i = start; i <= end; i++){
      if (check_unary(i) == 1){
         count++;
      }
   }
   return count;
}
int main(){
   int start = 200, end = 400;
   cout<<"Count of Unary Numbers in a Range are: "<<Unary_range(start, end);
   return 0;
}

輸出

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

Count of Unary Numbers in a Range are: 31

更新於:2021年1月5日

165 次瀏覽

開始您的職業生涯

完成課程獲得認證

開始學習
廣告