C++中计算数字个数,使得数字与其数字之和的差值不小于L
给定一个数字N和另一个数字L。目标是在1到N之间找到那些数字本身与其各位数字之和的差值不小于L的数字。
如果N=23,L=10,则此类数字的个数为4。
23-(2+3)=18, 22-(2+2)=18, 21-(2+1)=18, 20-(2+0)=18.
以上所有数字都满足条件
但是19-(1+9)=9小于L,类似地,18,17……1。
让我们通过例子来理解
输入 − N=30 L=19
输出 − 数字与其数字之和的差值不小于L的数字个数为 − 1
解释 − 只有30满足条件,30-(3+0)=27 > 19
输入 − N=123330 L=5466
输出 − 数字与其数字之和的差值不小于L的数字个数为 − 6841
下面程序中使用的算法如下:
使用二分查找找到第一个满足条件的数字。如果该数字为num,则num+1及之后的所有数字也满足该条件。
如果任何当前中间值满足条件,则中间值和结束值之间的所有数字也满足此条件,因此我们可以简单地将end-mid+1添加到计数中。
将num和L作为长整型变量。
函数Digit_sum(LL num)接受一个数字num并返回其各位数字之和。
将初始和设置为total=0。
使用while循环,将余数num%10添加到total中,并将num减少10。重复此操作,直到num>0。
返回total作为num的各位数字之和。
函数Less_than_L(LL num, LL L)接受一个数字num和一个数字L,并返回数字与其数字之和的差值不小于L的数字个数。
将初始计数设置为0。
使用while循环实现二分查找,其中start=1,end=num。
计算中间数为temp=(start+end)/2。
如果temp与其数字之和的差值不小于L,则所有大于temp的数字也满足相同条件。
包括temp在内的此类数字的个数为num-temp+1。将其添加到计数中。并将end设置为temp-1。
否则,将start设置为temp+1。
在二分查找结束时,count将包含数字与其数字之和的差值不小于L的数字个数。
返回count作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int Digit_sum(LL num){
LL total = 0;
while (num > 0){
total += num % 10;
num = num/10;
z}
return total;
}
LL Less_than_L(LL num, LL L){
LL count = 0;
LL start = 1;
LL end = num;
while (start <= end){
LL temp = (end + start) / 2;
LL temp_2 = temp - Digit_sum(temp);
if (temp_2 >= L){
count = num - temp + 1;
end = temp - 1;
}
else{
start = temp + 1;
}
}
return count;
}
int main(){
LL num = 234516;
LL L = 235;
cout<<"Count of Numbers such that difference between the number and sum of its digits not
less than L are: "<< Less_than_L(num, L);
return 0;
}输出
如果运行以上代码,将生成以下输出:
Count of Numbers such that difference between the number and sum of its digits not less than L are: 234267
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP