使用 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP