計算從1到n中,出現某位數字的次數

  • 出現1-9中某位數字次數的算法
/**
     * @param input 整數n(1 ≤ n ≤ 1,000,000,000)
     * @return 1-9中某個數字在數列中出現的次數
     */
    public int calcCount(int input, int x) {
        int count = 0;
        int temp;

        // 依次從個位往上開始計算
        for (int i = 1; (temp = input / i) != 0; i *= 10) {
            count += (temp / 10) * i;

            int current = temp % 10;

            if (current > x) {
                // 還會出現i次
                count += i;
            } else if (current == x) {
                // (input - temp * i)表明當前位置的低位數字
                count += input - temp * i + 1;
            }
        }

        Log.d(TAG, "calcCount() called with: input = [" + input + "], count = [" + count + "]");
        return count;
    }
  • 出現數字0出現次數的算法
/**
     * @param input 整數n(1 ≤ n ≤ 1,000,000,000)
     * @return 0在數列中出現的次數
     */
    public int calcZeroCount(int input) {
        int count = 0;
        int temp;

        // 依次從個位往上開始計算,至最高位-1爲止
        for (int i = 1; (temp = input / i) / 10 != 0; i *= 10) {
            count += (temp / 10) * i;

            if (temp % 10 == 0) {
                // (input - temp * i)表明當前位置的低位數字,去除首位爲0的數字
                count += input - temp * i + 1 - i;
            }
        }

        return count;
    }
  • 出現0-9中某位數字次數的綜合算法
public int count(int input, int x) {
        int count = 0;
        int temp;

        // 依次從個位往上開始計算
        for (int i = 1; (temp = input / i) != 0; i *= 10) {
            // 高位數字
            int high = temp / 10;
            if (x == 0) {
                if (high != 0) {
                    high--;
                } else {
                    break;
                }
            }
            count += high * i;

            int current = temp % 10;

            if (current > x) {
                count += i;
            } else if (current == x) {
                // (input - temp * i)表明當前位置的低位數字
                count += input - temp * i + 1;
            }
        }

        Log.d(TAG, "count() called with: input = [" + input + "], count = [" + count + "]");
        return count;
    }
相關文章
相關標籤/搜索