1049 Counting Ones (30分)【找规律】
1049 Counting Ones (30分)
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~n的所有数字中出现1的个数。我们肯定不能列举1到n的所有数来判断1的个数,这样一定会超时。我们可以通过以下规律来进行计算:
1.假设我们需要计算的数为n,且是一个m位的数,从低到高枚举n的每一位,对每一位计算1~n中该位为1的数的个数。
2.设当前处理至k位,,那么记left为第k位的高位所表示的数,now为第k位的数,right为第k位的低位所表示的数,然后根据当前第k位(now)的情况分为三类讨论:
①若now==0,则ans+=left*a。
②若now==1,则ans+=left*a+right+1。
③若now>=2,则ans+=(left+1)*a。
#include<iostream>
using namespace std;
int main()
{
int n, a = 1, ans = 0;
int left, now, right;
cin >> n;
while (n / a != 0)
{
left = n / (a * 10);
now = n / a % 10;
right = n%a;
if (now == 0)
ans += left*a;
else if (now == 1)
ans += left*a + right + 1;
else ans += (left + 1)*a;
a *= 10;
}
cout << ans << endl;
return 0;
}

浙公网安备 33010602011771号