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; } }
LeetCode(233):Number of Digit One
原文:http://www.cnblogs.com/Lewisr/p/5245668.html