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;
        }
    
  • 相关阅读:
    win7 删除Windows服务的方法
    如何对SQL Server 2005进行设置以允许远程连接(转载)
    MySql实现远程连接
    OpenCV训练分类器制作xml文档
    Ms SQL Server 约束和规则
    PowerDesigner实用技巧小结(4)
    企业级技术解决方案:hbase+es
    ES的聚合操作
    es之过滤器
    es之得分(加权)
  • 原文地址:https://www.cnblogs.com/coderwjq/p/7714464.html
Copyright © 2011-2022 走看看