51nod-1009 數字1的數量

基準時間限制:1 秒 空間限制:131072 KB 分值: 5 難度:1級算法

給定一個十進制正整數N,寫下從1開始,到N的所有正數,計算出其中出現所有1的個數。
例如:n = 12,包含了5個1。1,10,12共包含3個1,11包含2個1,總共5個1。
Input
輸入N(1 <= N <= 10^9)
Output
輸出包含1的個數
Input示例
12
Output示例
5
從低位一步步往高位推
#include <stdio.h>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
int main()
{
	int n;
	int t,tn;
	LL ans = 0;
	int mul = 1;
	scanf ("%d",&n);
	tn = n;
	while (tn)
	{
		t = tn % 10;
		if (t == 0)
			ans += n / (mul * 10) * mul;		//高位數字 
		else if (t == 1)
		{
			ans += n / (mul * 10) * mul;
			ans += (n % mul) + 1;
		}
		else		//只與高位有關 
			ans += (n / (mul * 10) + 1) * mul;
		mul *= 10;
		tn /= 10;
//		printf ("%lld\n",ans);
	}
	printf ("%lld\n",ans);
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章