intcode统计数字 java

来源:互联网 发布:linux tail f n 100 编辑:程序博客网 时间:2024/06/03 17:46

计算数字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)

标签 
枚举法
程序:

public class Solution {     /**     * @param : An integer     * @param : An integer     * @return: An integer denote the count of digit k in 1..n     */    public int digitCounts(int k, int n) {        // write your code here        int count = 0;        for(int i=0; i<=n; i++){            int j = i;            if(j<10){                if(j == k){                    count++;                }                }else{                while(j>0){                    //从最低位开始查找如果符合条件则跳出while语句                    if(j%10 == k){                        count++;                    }                    j = j/10;                }            }        }        return count;    }};