51Nod 1009:1009 数字1的数量 (思维)

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 <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#define ll long long
#define ms(a) memset(a,0,sizeof(a))
#define pi acos(-1.0)
#define INF 0x3f3f3f3f
const double E=exp(1);
const int maxn=1e6+10;
using namespace std;
int main(int argc, char const *argv[])
{
	ios::sync_with_stdio(false);
	int n;
	cin>>n;
	ll ans=0;
	int N=n;
	int vis=1;
	while(N)
	{
		int res=N%10;
		if(res==0)
			ans+=n/(vis*10)*vis;
		else if(res==1)
		{
			ans+=n/(vis*10)*vis;
			ans+=n%vis+1;
		}
		else
		{
			ans+=(n/(vis*10)+1)*vis;
		}
		N/=10;
		vis*=10;
	}
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wang_123_zy/article/details/81268294