[51 nod]1009 数字1的数量

基准时间限制: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
之前一直不明白为什么要循环,原来自己把题解看得太死了,百位是举例子,意思是判断每一个当前的数字都得这么算。。。
 1 #include<bits/stdc++.h>
 2 #define LL long long 
 4 using namespace std;
 5 LL f(LL n) {
 6         LL count = 0;
 7         LL i = 1;
 8         LL current = 0, after = 0, before = 0;
 9         //int t=0;
10         while ((n / i) != 0) {
11             current = (n / i) % 10;
12             before = n / (i * 10);
13             after = n - (n / i) * i;
14             if (current > 1)
15                 count = count + (before + 1) * i;
16             else if (current == 0)
17                 count = count + before * i;
18             else if (current == 1)
19                 count = count + before * i + after + 1;
20             i = i * 10;
21             //printf("t:%d before:%d current:%d after:%d count:%d
",++t,before,current,after,count);
22         }
23         return count;
24 }
25 int main(){
26     LL n;
27     cin>>n;
28     cout<<f(n)<<endl;
29 }
原文地址:https://www.cnblogs.com/zhien-aa/p/5679808.html