Java implementation of a number of digital LeetCode 233

233. The number of the number 1

Given an integer n, is less than the calculated number of all non-negative integer equal to n the number 1 appears.

Example:

Input: 13
Output: 6
Explanation: number 1 appears in the following numbers: 1, 10, 11, 12, 13.

On "Beauty of Programming" says:

Setting N = abcde, respectively, wherein abcde of decimal numbers of each bit.
If you want to calculate the number 1 appears on one hundred, it is influenced by three areas: the numbers on the one hundred, one hundred or less (lower) figures, more than one hundred (high) number.
If the number is one hundred possible on zero, one hundred the number 1 is determined by the higher position. For example: 12013, you can know the situation one hundred appear 1 might be: 100 199,1100 1199,2100 2199 ,, ..., 11100 11199, a total of 1200. Can be seen (12) is determined by the higher digit and higher digits is equal to (12) multiply the current number of bits (100). Note: High figures do not include the current position
if the number of one hundred the number is likely to appear on the 1 1, one hundred not only by the higher position but also by the impact of low impact. For example: 12113, then you know that one hundred cases by the high impact occurs is: 100 199,1100 1199,2100 2199 ,, ..., 11100 11199, a total of 1200. And as in the case above, and is equal to the higher digits (12) multiply the current number of bits (100). But also by low impact, one hundred cases occur is 1: 12100 ~ 12113, a total of 14, equal to the lower digit (13) +1. Note: this does not include the lower digit number
if the number is greater than one hundred one (2 9), on the occurrence of a case where only the higher-bit one hundred decisions, such as 12213, the Case 1 occurs one hundred is: 100 199,1100 1199,2100 2199, ..., 11100 11199,12100 12199, a total of 1300, and equal to higher digit + 1 (12 + 1) times the current number of bits (100)



class Solution {
    public int countDigitOne(int n) {
        if (n < 1)
            return 0;
        int len = getLenOfNum(n);
        if (len == 1)
            return 1;
        int tmp = (int) Math.pow(10, len - 1);
        int first = n / tmp; // 获取n的最高位数字
        int firstOneNum = first == 1 ? n % tmp + 1 : tmp; // 获取n的最高位为1时有多少个数字
        int otherOneNUm = first * (len - 1) * (tmp / 10); // 在介于n % tmp到n之间的数字中,除了最高位为1,其余各个数字分别为1 的总数和
        return firstOneNum + otherOneNUm + countDigitOne(n % tmp);
    }
    private int getLenOfNum(int n) {
        int len = 0;
        while (n != 0) {
            len++;
            n /= 10;
        }
        return len;
    }
}
发布了1371 篇原创文章 · 获赞 1万+ · 访问量 135万+

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104616379
233