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.
Input Specification:
Each input file contains one test case which gives the positive N (≤230 ).
Output Specification:
For each test case, print the number of 1’s in one line.
Sample Input:
12
Sample Output:
5
思路
千万不要被吓到了,害怕而不敢分析。其实就是简单排列组合,以每位为1为中心。
千万注意,每次只统计某一位上1在[1,N]所有数字中出现的次数,仅仅是该位上的,并没有统计其他位上的,因此不会导致重复。
★★eg:N=13
个位1:{1,11} 2个
十位1:{10,11,12,13} 4个
共2+4=6个
其中11用了两次,看似重复了,其实并没有,因为第一次统计的是11个位上的1,第二次统计11十位上的1。
正好统计两次,而11确实有2个1呀
#include<bits/stdc++.h>
using namespace std;
int main(){
int n, m, p=1, ans=0, high, low, self;
cin >> n;
m = n; //备份 以便求高低位
while (n)
{
self = n % 10; //当前位
high = m / (p * 10); //计算高位
low = m % p; //计算低位
if (self < 1)
ans += high * p; //小于1 高位*数量级
else if (self == 1)
ans += high * p + (low + 1);
// 等于1 高位*数量级+(低位+1) 后面的小部分单独考虑为(低位+1)
else
ans += (high + 1) * p; // 大于1 (高位+1)*数量级
p *= 10; //当前数量级+1
n /= 10;
}
cout << ans;
return 0;
}