题目描述
The task is simple: given any positive integer N, you are supposed to count the total number of 1’s in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1’s in 1, 10, 11, and 12.
输入
Each input file contains one test case which gives the positive N ( < = 2 30 <=2^{30} <=230).
输出
For each test case, print the number of 1’s in one line.
思路
这道题看似特变简单,但实际方法很巧妙
我这里写了下,大概每次得移动10位,来判断,当B>1的时候我们可以发现,取B=1则此时A取(0-A)都可,若B=1,则可以发现A这个时候取0-A-1时仍然全部都有1,但当A等于A时,B=1,C只能取0-C那么多个数字,因此加上C+1。当B=0时,要有1的话,A就不能等于A(A若等于A则这个数超过范围了),因此只能取0-A-1,所以如上述所示。
代码
#include<iostream>
#include<cstdio>
#include<stdlib.h>
using namespace std;
long long ans = 0;
long long N;
int main()
{
cin >> N;
long long A, B, C;
C = 0;
long long i = 1;
while (N / i)
{
B = (N/i) % 10;
A = N / (i*10);
C = N % i;
if (B > 1)
{
ans += (A + 1) * i;
}
else if (B == 1)
{
ans += A * i + C + 1;
}
else
{
ans += A * i;
}
i *= 10;
}
printf("%lld\n", ans);
}