[LeetCode 233] Number of Digit One

来源:互联网 发布:淘宝差评店主报复 编辑:程序博客网 时间:2024/05/16 07:38

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.


 public int countDigitOne(int n) {        int res = 0, a = 1, b = 1;        while (n > 0) {            res += (n + 8) / 10 * a;            if(n%10 == 1) res +=b;            b += n % 10 * a;            a *= 10;            n /= 10;        }        return res;    }



0 0
原创粉丝点击