从1到n整数中1出现的个数
整数中1出现的次数(从1到n整数中1出现的次数)
http://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6
参考了力扣区路飞大佬的题解:
public class Solution { public int NumberOf1Between1AndN_Solution(int n) { int digit = 1, res = 0; int high = n / 10, cur = n % 10, low = 0; while(high != 0 || cur != 0){ if(cur == 0) res += high * digit; else if(cur == 1) res += high * digit + low + 1; else res += (high + 1) * digit; low += cur * digit; cur = high % 10; high /= 10; digit *= 10; } return res; } }
时间复杂度: 数字N的位数: O(log10N) = O(logN)
空间复杂度: O(1)