LeetCode-Number of Digit One-解题报告

本文提供了一种方法来计算从1到任意整数n中数字1出现的总次数,通过逐位分析实现高效计算。

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

原题链接 https://leetcode.com/problems/number-of-digit-one/

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 


求出1~n所有数中1出现的个数。


最一般的方法当然是一个一个数的去数。


还有一种方法就是数每一个数位上1出现的个数。

对于一个数 abcd

当 d > 1的时候 个位上出现1的个数为 (abc + 1)*1

当d = 1 的时候 个位上出现1的个数为 abc * 1 + 0 + 1, 0表示 d后面的数。对于11 来说,个位上出现1的数为 11,1

当d = 0的时候 个位上出现1的个数为 abc * 1

对于其它数位,相对的1变为10,100,1000..

class Solution {
public:
    int countDigitOne(int n) {
		long long ans = 0, base = 1, last = 0;
		while (n)
		{
			int t = n % 10;
			n /= 10;
			if (t > 1)ans += (n + 1) * base;
			else if (t == 1)ans += n*base + last + 1;
			else ans += n*base;
			last = t*base + last;
			base *= 10;
			
		}
		return ans;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值