PTA_PAT甲級_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(≤2^30).

Output Specification:
For each test case, print the number of 1’s in one line.

Sample Input:

12

Sample Output:

5

題意:
給出一個數,輸出比它小的所有數的所有位中數字1出現的次數

分析:
從所給數的最低位起按位計算

代碼:

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
    int N, a=1, ans=0;//a爲10的當前位數 
    int left, now, right;
    cin>>N;
    while(N/a!=0){
    	left = N/(a*10);//left爲當前位左邊的部分
		now = (N/a)%10;//now爲當前位
		right = N%a;//right爲當前位右邊位
		if(now==0) ans += left*a;
		//左邊從0變化到比現在小1,不管右邊是多少,當前位都可以取到1 
		else if(now==1) ans += left*a + right + 1;
		//左邊從0到比現在小1乘右邊位數,加上左邊爲當前值加右邊值從0到現在值 
		else ans += (left+1)*a;//左邊從0到現在不管右邊取何值都可以
		a *= 10; 
	}
	cout<<ans;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章