Number of Digit One 【leetcode】



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.

Hint:

Show Hint
  1. Beware of overflow.

因为耗时过长被拒掉的代码

public class Solution {
    public int countDigitOne(int n) {
        int count=0;
        for(int i=0;i<=n;i++){
         String temp=new Integer(i).toString();
            for(int j=0;j<temp.length();j++){
             if(temp.charAt(j)=='1')
             count++;
            }
           
        }
        return count;
    }
}

要动脑思考,优化一下!改进的方法

  public int countDigitOne(int n) {
    
       if(n<=0)return 0;
       if(n<10)return 1;
       int index=(int)Math.pow(10, new Integer(n).toString().length()-1);
       int count=n/index;
       int oneIndex=index;
       if(count==1)
        oneIndex=n-index+1;
        int sum=countDigitOne(index-1)*count+oneIndex+countDigitOne(n-count*index);
        return sum;
    }

此处是从discuss看到的思路

For example '8192':

1-999 -> countDigitOne(999)

1000-1999 -> 1000 of 1s + countDigitOne(999)

2000-2999 -> countDigitOne(999)

.

.

7000-7999 -> countDigitOne(999)

8000-8192 -> countDigitOne(192)

Count of 1s : countDigitOne(999)*8 + 1000 + countDigitOne(192)

Noticed that, if the target is '1192':

Count of 1s : countDigitOne(999)*1 + (1192 - 1000 + 1) + countDigitOne(192)

(1192 - 1000 + 1) is the 1s in thousands from 1000 to 1192.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值