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
#include <string>#include <iostream>#include <math.h>using namespace std;string str;int GetLeftNum(int a) {int left = 0;for (int i = 0; i < a; i++) {left *= 10;left += str[i] - '0';}return left;}int GetRightNum(int b) {int right = 0;for (int i = b+1; i < str.length(); i++) {right *= 10;right += str[i] - '0';}return right;}int main(void) {cin >> str;if (str.length() == 0) {cout << 1;return 0;}int oneCnt = 0;int left = 0, right = 0;for (int i = 0; i < str.length(); i++) {left = GetLeftNum(i);right = GetRightNum(i);if (str[i] - '0' > 1) {oneCnt += (left + 1)*pow(10, str.length() - i - 1);}else if (str[i] == '1') {oneCnt+= (left)*pow(10, str.length() - i - 1)+right+1;}else {oneCnt += (left)*pow(10, str.length() - i - 1);}}cout << oneCnt;return 0;}
浙公网安备 33010602011771号