Number of Digit One 【leetcode】

原创 2015年07月09日 10:31:36


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.



LeetCode No.233 Number of Digit One

LeetCode No.233 Number of Digit One

leetcode解题笔记:Number of Digit One

233.Number of Digit One Given an integer n, count the total number of digit 1 appearing in all non...

[LeetCode]233.Number of Digit One

题目Given an integer n, count the total number of digit 1 appearing in all non-negative integers less ...

[分析总结:leetcode-Number of Digit One]寻找整数1到n之间所有数字中1出现的次数

leetcode原题链接:https://leetcode.com/problems/number-of-digit-one/ 题目描述: 要求寻找整数1到n之间所有数字中,1出现的次数。如给定...

Leetcode Number of Digit One

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

leetcode -- Number of Digit One -- 数学题,找规律

https://leetcode.com/problems/number-of-digit-one/参考http://www.cnblogs.com/grandyang/p/4629032.htmlh...
  • xyqzki
  • xyqzki
  • 2015年12月16日 17:11
  • 268

LeetCode-233.Number of Digit One

https://leetcode.com/problems/number-of-digit-one/ Given an integer n, count the total number o...

LeetCode Algorithms 233. Number of Digit One 题解

题目:Given an integer n, count the total number of digit 1 appearing in all non-negative integers less...

[LeetCode]Number of Digit One,解题报告

题目Given an integer n, count the total number of digit 1 appearing in all non-negative integers less ...

算法Week02.04 - LeetCode 233. Number of Digit One

算法Week02.04 - LeetCode 233. Number of Digit One
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Number of Digit One 【leetcode】
举报原因:
原因补充:

(最多只允许输入30个字)