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.

输入

Each input file contains one test case which gives the positive N ( < = 2 30 <=2^{30} <=230).

输出

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

思路

这道题看似特变简单,但实际方法很巧妙
在这里插入图片描述
我这里写了下,大概每次得移动10位,来判断,当B>1的时候我们可以发现,取B=1则此时A取(0-A)都可,若B=1,则可以发现A这个时候取0-A-1时仍然全部都有1,但当A等于A时,B=1,C只能取0-C那么多个数字,因此加上C+1。当B=0时,要有1的话,A就不能等于A(A若等于A则这个数超过范围了),因此只能取0-A-1,所以如上述所示。

代码

#include<iostream>
#include<cstdio>
#include<stdlib.h>
using namespace std;
long long ans = 0;
long long N;
int main()
{
	cin >> N;
	long long A, B, C;
	C = 0;
	long long i = 1;
	while (N / i)
	{
		B = (N/i) % 10;
		A = N / (i*10);
		C = N % i;
		if (B > 1)
		{
			ans += (A + 1) * i;
		}
		else if (B == 1)
		{
			ans += A * i + C + 1;
		}
		else
		{
			ans += A * i;
		}
		i *= 10;
	}
	printf("%lld\n", ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值