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
代码:
#include <iostream>
using namespace std;
typedef long long LL;
LL CountOne(LL n)
{
LL count = 0;
LL i = 1;
LL current = 0,after = 0,before = 0;
while((n / i) != 0)
{
current = (n / i) % 10;
before = n / (i * 10);
after = n - (n / i) * i;
if (current > 1)
count = count + (before + 1) * i;
else if (current == 0)
count = count + before * i;
else if(current == 1)
count = count + before * i + after + 1;
i = i * 10;
}
return count;
}
int main()
{
LL n;
cin>>n;
cout<<CountOne(n)<<endl;
return 0;
}