zoukankan      html  css  js  c++  java
  • 计算从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;
        }
    
  • 相关阅读:
    实验二Step1-有序顺序表
    0330复利计算4.0(改)
    0330复利计算4.0单元测试
    实验一 命令解释程序的编写
    《构建之法》之第1、2、3章读后感
    0408-汉堡包的方式评价合作伙伴
    0406-复利计算5.0
    0405—软件工程 《构建之法》 第四章读后感
    03-29复利计算单元测试
    03-25实验一、命令解释程序的编写
  • 原文地址:https://www.cnblogs.com/coderwjq/p/7714464.html
Copyright © 2011-2022 走看看