LintCode——数字统计
数字统计:计算数字k在0到n中的出现的次数,k可能是0~9的一个值
样例:例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次(1, 10, 11, 12)
1、Python
1 class Solution: 2 """ 3 @param: : An integer 4 @param: : An integer 5 @return: An integer denote the count of digit k in 1..n 6 """ 7 8 def digitCounts(self, k, n): 9 # write your code here 10 sum = 0 11 k=str(k) 12 for i in range(n + 1): 13 s = str(i) 14 for j in s: 15 if(j==k): 16 sum+=1 17 return sum
2、Java
说明:
设一个整数为abcdef(六位数),current表示当前正在统计的i位上的数字大小(i=10时,current=e i=1000时,current=c)
before为current之前的所有数字,after为current之后的所有数字(current=d时,before=abc,after=ef)
举例:
534898 current=4 before=53 after=898
从个位开始统计。直到统计完所有位。
1 public class Solution { 2 /* 3 * @param : An integer 4 * @param : An integer 5 * @return: An integer denote the count of digit k in 1..n 6 */ 7 public int digitCounts(int k, int n) { 8 // write your code here 9 int current = 0,before = 0,after = 0; 10 int i = 1,count = 0; 11 int flag=1; 12 while(n/i != 0 || (n==0&&flag==1)){//n=0,k=0特殊情况处理 13 if(n==0){ 14 flag=0; 15 } 16 current = (n / i) % 10; 17 before = n / (i * 10); 18 after = n - before * (i * 10) - current * i; 19 if(k!=0 || before!=0){ 20 if(current > k) 21 count += (before + 1) * i; 22 else if(current < k) 23 count += before * i; 24 else 25 count += before * i + after + 1; 26 } 27 else{ 28 if(after!=0) 29 count += 0; 30 else 31 count += 1; 32 } 33 i *= 10; 34 } 35 return count; 36 } 37 };