基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的个数。
例如:n = 12,包含了5个1。1,10,12共包含3个1,11包含2个1,总共5个1。
Input
输入N(1 <= N <= 10^9)
Output
输出包含1的个数
Input示例
12
Output示例
5
详解请看大牛博客:http://www.cnblogs.com/jy02414216/archive/2011/03/09/1977724.html
之前一直不明白为什么要循环,原来自己把题解看得太死了,百位是举例子,意思是判断每一个当前的数字都得这么算。。。
#include<bits/stdc++.h>
#define LL long long
using namespace std;
LL f(LL n) {
LL count = ;
LL i = ;
LL current = , after = , before = ;
//int t=0;
while ((n / i) != ) {
current = (n / i) % ;
before = n / (i * );
after = n - (n / i) * i;
if (current > )
count = count + (before + ) * i;
else if (current == )
count = count + before * i;
else if (current == )
count = count + before * i + after + ;
i = i * ;
//printf("t:%d before:%d current:%d after:%d count:%d\n",++t,before,current,after,count);
}
return count;
}
int main(){
LL n;
cin>>n;
cout<<f(n)<<endl;
}