【Offer】[43] 【1~n整数中1出现的次数】

题目描述

  输入一个整数n,求1~n这n个整数的十进制表示中1出现的次数。例如,输入12, 1~12这些整数中包含1的数字有1、10、11和12,1一共出现了5次。

牛客网刷题地址

思路分析

  对于整数n,我们将这个整数分为三部分:当前位数字cur,更高位数字high,更低位数字low,如:对于n=21034,当位数是十位时,cur=3,high=210,low=4。

  我们从个位到最高位 依次计算每个位置出现1的次数:

  1)当前位的数字等于0时,例如n=21034,在百位上的数字cur=0,百位上是1的情况有:00100~00199,01100~01199,……,20100~20199。一共有21100种情况,即high100;

  2)当前位的数字等于1时,例如n=21034,在千位上的数字cur=1,千位上是1的情况有:01000~01999,11000~11999,21000~21034。一共有21000+(34+1)种情况,即high1000+(low+1)。

  3)当前位的数字大于1时,例如n=21034,在十位上的数字cur=3,十位上是1的情况有:00010~00019,……,21010~21019。一共有(210+1)10种情况,即(high+1)10。

  这个方法只需要遍历每个位数,对于整数n,其位数一共有lgn个,所以时间复杂度为O(logn)。

测试用例

  1. 功能测试:输入5、10、55、99等。
  2. 边界值测试:输入0、1等。
  3. 性能测试:输入较大的数字,如10000、21235 等。

Java代码

public class Offer043 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

    public static int NumberOf1Between1AndN_Solution(int n) {
        return Solution1(n);
    }


    private static int Solution1(int n) {
        
        int count=0;
        for(int i=1;i<=n;i*=10) {
            int high = n/(i*10);
            int low = n%i;
            int cur = (n/i)%10;
            if(cur == 0) {
                count+=high*i;
            }else if(cur==1) {
                count+=high*i+(low+1);
            }else {
                count+=(high+1)*i;
            }
        }
        return count;
    }

    private static void test1() {
        int times = NumberOf1Between1AndN_Solution(12);
        System.out.println(times);
    }

    private static void test2() {
        System.out.println(NumberOf1Between1AndN_Solution(0));
    }
    private static void test3() {
        System.out.println(NumberOf1Between1AndN_Solution(21345));
    }
}

代码链接

剑指Offer代码-Java

原文地址:https://www.cnblogs.com/haoworld/p/offer43-1n-zheng-shu-zhong1chu-xian-de-ci-shu.html