Java implements the number of occurrences of 1 in an integer (the number of occurrences of 1 in an integer from 1 to n)

Find the number of occurrences of 1 in the integers from 1 to 13, and count the number of occurrences of 1 in the integers from 100 to 1300? For this reason, he counted the numbers containing 1 in 1~13. There are 1, 10, 11, 12, and 13, so there are 6 times in total, but he can't do anything about the latter problem. ACMer wants you to help him and make the problem more general, and can quickly find the number of occurrences of 1 in any interval of non-negative integers.

code

    public static long calAllAppearSumOfk(int left, int right, int k) {
        int start = 0;
        int end = 0;
        if (left < right) {
            start = left;
            end = right;
        } else {
            start = right;
            end = left;
        }
        long sum = 0;
        for (int i = start; i <= end; i++) {
            sum + = calAppearSumOfk (i, k);
        }
        return sum;
    }

    private static int calAppearSumOfk(int n, int k) {
        int sum = 0;
        // Count the number of occurrences of k by remainder and division
        // k is between [1, 9], so use 10 as base
        // Multiply by 10 to get a single digit value, such as 11 % 10 = 1, 121 % 10 = 1
        // Divide by 10 to eliminate the number of digits already calculated, such as 11 / 10 = 1, 121 / 10 = 12
        while (n > 0) {
            // Find the remainder of 10, if the remainder is equal to k, it means that k appears in the ones digit
            if (n % 10 == k) {
                sum++;
            }
            // Divide by 10, save the result, remove the current ones, end when n==0
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        long sum = calAllAppearSumOfk(1, 13, 1);
        System.out.print(sum);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325940013&siteId=291194637