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:12Sample Output:
5
我的做法是,可以按照数的位一位一位求该位所贡献的‘1’的个数;
例如:
12 --> '1'贡献了3次,'2'贡献了2次,所以一共有5个‘1’;
203 --> ‘2’贡献了100次,‘0’贡献了20次,‘3’贡献了21次,所以一共有141个‘1’;
规律其实很简单,个位每10次贡献1个‘1’,十位每百次贡献10个‘1’,百位每千次贡献100个‘1’...依此类推;
利用上诉规律不难写出相应的算法实现,但是要注意的是,没有达到贡献周期的位,要判断该位是否大于1(即是否超过贡献周期);
例如:
‘12’ 中的‘1’因为没有超过贡献周期,所以只贡献了3个‘1’(即‘10’、‘11’、‘12’中十位的‘1’)而不是10个,而‘2’因为超过了贡献周期中的分界,所以贡献了2个‘1’(即‘1’、‘11’中个位的‘1’);
具体实现代码如下:
/************************************
This is a test program for anything
Enjoy IT!
************************************/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <list>
#include <set>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
//ifstream cin;
//cin.open("in.txt");
//ofstream cout;
//cout.open("out.txt");
//
// TO DO Whatever You WANT!
int n;
while (cin >> n)
{
int sum = 0;
int base = 1; // 基数,用来记录第几位
int m = n;
while (n != 0) // 每次去掉一位低位
{
int temp = n / 10;
if (n % 10 > 1) // 如果准备去掉的低位大于1,则加上当前位置的基数
sum += base;
else if (n % 10 == 1) // 如果地位等于1,则加上原数尾部的个数
sum += m % base + 1;
sum += temp * base; // 当前位置所经过的轮数
base *= 10; // 基数增长
n /= 10; // 去掉低位
}
cout << sum << endl;
}
//
// system("pause");
return 0;
}