LeetCode(233):Number of Digit One

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,小于等于n的正整数只1的个数。

思路:参考http://www.07net01.com/2015/07/886667.html

代码:

public class Solution {
    public int countDigitOne(int n) {
     if(n<=0) return 0;
     long count = 0;
        long factor = 1;
        
        while (n / factor != 0) {
            long lower = n % factor;
            long cur = (n / factor) % 10;
            long higher = n / (factor * 10);
            
            if (cur < 2) {
                count += higher * factor;
                if (cur == 1) count += lower+1;
            } else {
                count += (higher+1) * factor;
            }
            factor *= 10;
        }
        return (int) count;
    }
     
}
posted @ 2016-03-05 19:53  Lewisr  阅读(104)  评论(0编辑  收藏  举报