给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的个数。
Input
输入N(1 <= N <= 10^9)
Output
输出包含1的个数
Sample Input
Sample Output
大牛:
点击打开链接
代码:
例如:n = 12,包含了5个1。1,10,12共包含3个1,11包含2个1,总共5个1。
12
5
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long ll;
ll solve(long n){
ll cnt=0;
ll i=1;
ll cur=0,high=0,low=0;
while((n/i)!=0){
cur=(n/i)%10;
high=n/(i*10);
low=n-(n/i)*i;
if(cur>1) cnt+=(high+1)*i;
else if(cur==0) cnt+=high*i;
else if(cur==1) cnt+=high*i+low+1;
i*=10;
}
return cnt;
}
int main(){
ll n;
scanf("%lld",&n);
printf("%lld\n",solve(n));
return 0;
}