Leetcode problem: Enter an integer n and find the number of occurrences of 1 in the decimal representation of the n integers from 1 to n.

  Calculate the number of each bit from low to high.

  Take 3104 as an example, divide it into three parts: high bit high, current bit cur, low bit low

  (1) When counting the number of occurrences of a single digit: high = 310; cur = 4, low = 0.

        When 0 ~ 309 changes, cur only has 1 case, so there are 310 1s, because cur = 4, so when the high bit is 310, there is also a 1; so the number of times 1 appears count = 311;

  (2) When calculating the tens place: high = 31, cur = 0, low = 4.

        Each time 0 ~ 30 changes, cur and low only have 10 1s when they are 10 ~ 19, because cur = 0, so when the high bit is 31, the maximum number is 3104, and there will be no 1, so the number of occurrences of the ten digit count = 31 * 10 = 310;

  (3) When calculating hundreds: high = 3, cur = 1; low = 4:

        Each time 0 ~ 2 changes, cur and low only have 100 1s when they are 100 ~ 199, because cur = 1, so when the high bit is 3, there are 5 1s in the hundreds, that is, 3100 ~ 3104, so 1 in the hundreds The number of times count = 3 * 100 + 5 = 305;

  (4) When counting thousands: high = 0, cur = 3, low = 104.

        Because cur = 3, there are 1000 1s when cur and low are 1000 ~ 1999, and count = 1000.

  Add up to get count = 1926.

 

  The algorithm is: i = 1, 10,100 ... represent the ones, tens, hundreds ...

      if(cur == 0) 

        count = high * i;

      if (cur == 1)

        count = high * i + low + 1;

      if (cur > 1)

        count = (high + 1) * i;

       

int countDigitOne(int n){
    int i = 1;
    int count = 0;
    while ((n / i != 0) {
        int high;
        int cur;
        int low;
        high = n / (i * 10);
        cur = (n / i) % 10;
        low = n - (n / i * i);
        
        if (cur == 0) {
            count += (high * i);
        } else if (cur == 1) {
            count += (high * i) + low + 1;
        } else if (cur > 1) {
            count += (high + 1) * i;
        }
        i *= 10;
    }
    return count;
}

2020/4/20

00:30

 

Guess you like

Origin www.cnblogs.com/zhengxunjie/p/12735299.html