233. Number of Digit One

网友投稿 611 2022-09-04

233. Number of Digit One

233. 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=abcde五位数字的时候,我们分析百位c,有三种情况:

1、c == 0的时候,比如12013,此时百位出现1的是:00 100 ~ 00 199, 01 100~01 199,……,11 100~ 11 199,共1200个,显然这个有高位数字决定,并且受当前位数影响; 个数就是 ab*100

2、c == 1的时候,比如12113,此时百位出现1的肯定包括c=0的情况,另外还需要考虑低位的情况即:00100 ~ 00113共14个; 个数等于ab*100+ de + 1

3、c >= 2的时候,比如12213,此时百位出现1的是:00 100 ~ 00 199, 01 100~01 199,……,11 100~ 11 199,12 100 ~ 12 199,共1300个,这个有高位数字决定,其实是加一,并且乘以当前位数; 个数就是 (ab+1)*100

总结起来,对于一个 n = abcde 来说,百位出现1的个数计算方法为 :

if(c==0) ans = ab*100; if(c==1) ans = ab*100+cd+1 if(c>1) ans = (ab+1)*100

class Solution { public int countDigitOne(int n) { if(n <= 0) return 0; int q = n; int x = 1; int ans = 0; int temp = 0; do{ temp = q%10; q/=10; if(temp == 0) ans+=q*x; else if(temp == 1) ans+=q*x + n%x + 1; else ans+=(q+1)*x; x*=10; } while (q > 0); return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:273. Integer to English Words
下一篇:程序员需要知道的缩写和专业名词(编程常用缩写)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~