计算从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;
    }
posted @ 2017-10-23 09:02  喳喳的夏天  阅读(328)  评论(0编辑  收藏  举报