【每天一道編程系列-2018.3.19】—— Digit Counts

【題目描述】



Count the number of k's between 0 and nk can be 0 - 9.


Example

if n = 12, k = 1 in

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

we have FIVE 1's (1, 10, 11, 12)




【題目大意】



計算數字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)




【本題答案】


package blog;

/**
 * @author yesr
 * @create 2018-03-20 上午12:13
 * @desc
 **/
public class Test0319 {

    public int digitCounts(int k, int n) {
        int cnt = 0;
        for (int i = k; i <= n; i++) {
            //分次計算每一個數中含有k的個數
            cnt += singleCount(i, k);
        }
        return cnt;
    }
    private int singleCount(int i, int k) {
        //排除0的情況
        if (i == 0 && k == 0)
            return 1;
        int cnt = 0;
        while (i > 0) {
            //判斷末尾是否爲k
            if (i % 10 == k) {
                cnt++;
            }
            //去掉末尾再次循環,直到去除完所有位跳出循環
            i = i / 10;
        }
        return cnt;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章