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 (<=230).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:
12
Sample Output:
5
思路:

这里要从数字的最高位开始,所以作为字符串输入。在计数1出现时,可分为纵向和横向,以34为例,纵向为01,11,21,31,横向为10,11,12,。。。,19,所以共14个。在这里,先判断其是否大于0:

1)大于0,计算:

     1.1)判断其是否等于‘1’:

             a)等于‘1’:先加上后几位最高的‘1’的个数,如34中的‘01’这个;再加上这位数后面的尾数个数,如‘123’中加上(23+1);

             b)大于‘1’:加上该位为‘1’时的个数,如‘34’中的10,11,12,。。,19,再加上后几位最高的‘1’的个数

2)不大于0,跳过

代码:

#include<iostream>
#include<string>
#include<cmath>
using namespace std;

int d[11] = { 0 };

int main()
{
	//最大的i位数所出现的1个数
	int i;
	d[1] = 1;
	for (i = 2; i <= 10; ++i)
	{
		d[i] = d[i - 1] * 10 + pow(10, i - 1);
	}
	//input
	string N;
	cin >> N;


	int num = 0;
	for (i = 0; i < N.size(); ++i)
	{
		//从最高位开始
		if (N[i] > '0')
		{
			//当前有大于0的数
			if (N[i] > '1')
			{
				//当前的数大于1,当前数是N.size()-i位
				num += pow(10,N.size()-i-1);
				num += (N[i] - '0')*d[N.size()-i-1];
			}
			else
			{
				//恰好当前为1,直接计算后面尾数
				num += d[N.size()-i-1]; //加上以0开头的部分
				int k = i + 1;
				int last = 0;
				for (; k < N.size(); ++k)
				{
					last = last * 10 + (N[k]-'0');
				}
				num += last + 1;
			}
		}
	}

	cout << num << endl;

	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值