LeetCode算法题目:Number of Digit One
来源:互联网 发布:真正刷钻软件 编辑:程序博客网 时间:2024/06/06 03:32
题目:
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.
思路:
考虑将n的十进制的每一位单独拿出讨论,每一位的值记为weight。
个位
从1到n,每增加1,weight就会加1,当weight加到9时,再加1又会回到0重新开始。那么weight从0-9的这种周期会出现多少次呢?这取决于n的高位是多少,看图:
以534为例,在从1增长到n的过程中,534的个位从0-9变化了53次,记为round。每一轮变化中,1在个位出现一次,所以一共出现了53次。
再来看weight的值。weight为4,大于0,说明第54轮变化是从0-4,1又出现了1次。我们记1出现的次数为count,所以:count = round+1 = 53 + 1 = 54 十位
对于10位来说,其0-9周期的出现次数与个位的统计方式是相同的,见图:
不同点在于:从1到n,每增加10,十位的weight才会增加1,所以,一轮0-9周期内,1会出现10次。即rount*10。
再来看weight的值。当此时weight为3,大于1,说明第6轮出现了10次1,则:
count = round*10+10 = 5*10+10 = 60
如果此时weight的值等于0(n=504),说明第6轮到0就停止了,所以:
count = round*10+10 = 5*10 = 50
如果此时weight的值等于1(n=514),那么第6轮中1出现了多少次呢?很明显,这与个位数的值有关,个位数为k,第6轮中1就出现了k+1次(0-k)。我们记个位数为former,则:
count = round*10+former +1= 5*10+4 = 55更高位
更高位的计算方式其实与十位是一致的,不再阐述。
总结
将n的各个位分为两类:个位与其它位。
对个位来说:
若个位大于0,1出现的次数为round*1+1
若个位等于0,1出现的次数为round*1
对其它位来说,记每一位的权值为base,位值为weight,该位之前的数是former,举例如图:
则:若weight为0,则1出现次数为round*base
若weight为1,则1出现次数为round*base+former+1
若weight大于1,则1出现次数为rount*base+base比如:
534 = (个位1出现次数)+(十位1出现次数)+(百位1出现次数)=(53*1+1)+(5*10+10)+(0*100+100)= 214
530 = (53*1)+(5*10+10)+(0*100+100) = 213
504 = (50*1+1)+(5*10)+(0*100+100) = 201
514 = (51*1+1)+(5*10+4+1)+(0*100+100) = 207
10 = (1*1)+(0*10+0+1) = 2
代码:
class Solution {public: int countDigitOne(int n) { if(n<1) return 0; int count = 0; int base = 1; int round = n; while(round>0){ int weight = round%10; round/=10; count += round*base; if(weight==1) count+=(n%base)+1; else if(weight>1) count+=base; base*=10; } return count; }};
- LeetCode算法题目:Number of Digit One
- Number of Digit One 【leetcode】
- [leetcode] Number of Digit One
- [LeetCode] Number of Digit One
- LeetCode ||Number of Digit One
- Number of Digit One -- leetcode
- *LeetCode-Number of Digit One
- [LeetCode] Number of Digit One
- Leetcode Number of Digit One
- Leetcode: Number of Digit One
- Leetcode Number of Digit One
- leetcode:Number of Digit One
- 《leetCode》: Number of Digit One
- Leetcode Number of Digit One
- Number of Digit One leetcode
- 算法Week02.04 - LeetCode 233. Number of Digit One
- leetcode 233: Number of Digit One
- Leetcode 233 Number of Digit One
- Java编程:深入理解final关键字
- C语言-预处理指令(Preprocessing Directive)-宏定义
- 玩转大数据_你需要了解这8种项目类型!
- WatchOS系统开发大全(5)-WKInterfaceController的生命周期
- 笔记4——vim编辑器
- LeetCode算法题目:Number of Digit One
- 读ini文件.
- 二分图 最大匹配 之最小点覆盖
- 安装orcle12C碰到“无法访问临时位置”的问题处理
- java内存区域划分
- 乒乓球
- Struts2动态参数封装
- 1090. Highest Price in Supply Chain (25)<BFS,DFS>
- [Leetcode] 319. Bulb Switcher 解题报告