1049 Counting Ones (30)(30 point(s)(cj)

本文介绍了一种计算从1到给定正整数N(N<=2^30)范围内所有数字中数字1出现次数的方法。通过分析每一位上的1出现的规律,递归地计算出最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1049 Counting Ones (30)(30 point(s))

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的个数,比如

  •  个位只有 1
  • 十位和个位共有 (9*1 +10^{1})(1-9 数的个位是1的数量 和十位是1的数量)+ 个位数量 1 = 20
  • 百位 (9*20 + 10^{2} )+ 20= 300;

此位不是1时 到此位时所有的有1的数数量 和此位是1是 数量和,重复数使得计算出数字中1的个数。

如果有大小限制的话。

此位为0时 没有增加数量,因为 012 就是 12 本身。

此位为1时,totalsum += (n%num+1) (就像123  从 100到 123);      totalsum += bitsum (就像 123 上十位个位 0-99中1的个数);

此位为>1时,totalsum += bitallsum (就是 100-199);  totalsum += (part)*bitsum (0-99含1个数×part);

#include <iostream>
#include <string>
using namespace std;
long long deal(long long n);
int main(){
	long long n;
	while (cin >> n)
		cout << deal(n) << endl;
	system("pause");
	return 0;
}
long long deal(long long n) {
	long long totalsum = 0;
	long long bitallsum = 1;
	long long bitsum = 0;
	long long num = 1;
	while (n/num) {
		long long part = (n / num) % 10 ;
		if (part == 1) {
			totalsum += (n%num+1);
			totalsum += bitsum;
		}
		else if(part > 1) {
			totalsum += bitallsum;
			totalsum += (part)*bitsum;
		}
		bitsum += (9 * bitsum + bitallsum);
		bitallsum *= 10;
		num *= 10;
	}
	return totalsum;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值