使用 C++ 統計數字與其各位數字之和的差大於特定值的數字個數


我們提供兩個數字 N,定義範圍 [1,N],以及 D,表示差值。目標是在範圍 [1,N] 中找到所有滿足 [數字 - (其各位數字之和)] > D 的數字。我們將透過遍歷從 1 到 N 的數字來實現這一點,併為每個數字使用 while 迴圈計算其各位數字之和。檢查數字和計算出的各位數字之和的差是否大於 D。

讓我們透過示例來理解。

輸入 

N=15 D=5

輸出 

Numbers such that difference b/w no. and its digit sum greater than value D: 6

解釋 

Numbers 10, 11, 12, 13, 14, 15 satisfy the condition. ( 10-1, 11-2, 12-3, 13-4, 14-5, 15-6 ) all differences are 9 which is greater than 5.

輸入 

N=20 D=10

輸出 

Only 20 satisfies the condition. 20-2=18 > 10.

解釋 

This is list of numbers divisible by all non-zero digits : 100 101 102 104 105 110 111 112 115 120 122 124 126 128 132 135 140 144 150 155 162 168 175 184 200

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

  • 我們獲取整數 N 和 D。

  • 函式 digitSum(int n, int d) 獲取變數 N、D 並返回 (num-digitsum) >d 的數字個數。

  • 將初始變數 count 初始化為 0,用於統計滿足條件的數字個數。

  • 將變數 digsum 初始化為 0。

  • 使用 for 迴圈遍歷數字範圍。i=1 到 i=n

  • 現在,對於每個數字 num=i,使用 while 迴圈檢查數字是否 >0。

  • 計算 digsum+=num%10。將 num=num/10 以新增下一個數字。

  • 在 while 迴圈結束時,檢查 ( i - digsum > d )。如果為真,則遞增 count。

  • 在所有迴圈結束時,count 將包含滿足條件的數字總數。

  • 返回 count 作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int digitSum(int n, int d){
   int count = 0;
   int digsum = 0;
   for (int i = 1; i <= n; i++){
      int num=i;
      digsum=0;
      while(num>0){
         digsum+=num%10; //sum of digits
         num=num/10;
      }
      if(i-digsum>d) //original number is i {
         count++;
         //cout<<i<<" ";
      }
   }
   return count;
}
int main(){
   int N = 20;
   int D = 8;
   cout <<"Numbers such that difference between number and its digit sum greater than specific value: "<<digitSum(N,D);
   return 0;
}

輸出

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

Numbers such that difference between number and its digit sum greater than specific value: 11

更新於: 2020年10月31日

526 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告

© . All rights reserved.