Hard-题目26:233. Number of Digit One

原创 2016年05月31日 23:37:25

题目原文:
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?
题目分析:
纯数学题,由@1401-高洪帆给出公式f(n)的数学形式,具体是什么我推不出来了,翻译成计算机代码将就看吧。
源码:(language:java)

public class Solution {
    public int countDigitOne(int n) {
        int[] powers = new int[]{0,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,2147483647};
        int k=0;
        if(n==2147483647)
            k=10;
        else {
            while(powers[k]<=n)
                k++;
        }

        if(n<=0)
            return 0;
        else if(n>=1 && n<10)
            return 1;
        else {
            k--;
            return countDigitOne(powers[k]-1)*(n/powers[k])+countDigitOne(n%powers[k])+(n>=2*powers[k]?powers[k]:n-powers[k]+1);
        }
    }

}

成绩:
0ms,7.97%,0ms,92.03%
cmershen的碎碎念:
听说acm中有很多题可以直接推出数学公式,但求职的机试中好像还是更侧重计算机算法吧。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

LeetCode-233.Number of Digit One

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

剑指offer 面试题32:从1到n整数中1出现的次数(leecode233. Number of Digit One) 题解

剑指offer 面试题32:从1到n整数中1出现的次数(Leecode233. Number of Digit One) 提交网址: http://www.nowcoder.com/prac...

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...

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

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

【LeetCode-233】Number of Digit One

一看到这道题就想到了动态规划,但是tle了,先看看我的python代码吧! class Solution(object): # 最容易想到的方法了(动态规划),但是tle了 def ...

LeetCode 233. Number of Digit One

原题网址:https://leetcode.com/problems/number-of-digit-one/ Given an integer n, count the total number...
  • jmspan
  • jmspan
  • 2016年04月06日 04:10
  • 260

leetcode 233: Number of Digit One

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

LeetCode No.233 Number of Digit One

LeetCode No.233 Number of Digit One

[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-Hard-2】【Number of Digit One】【1~N中‘1’出现次数】

第二题,中等难度,看到正确率略小于0.2就做了 233 Number of Digit One 19.5% Medium Given an integer n, count ...
  • hjy0125
  • hjy0125
  • 2015年07月21日 22:37
  • 335
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Hard-题目26:233. Number of Digit One
举报原因:
原因补充:

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