LeetCode-233 Number of Digit One

Title Description

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

 

Subject to the effect

Computing [0, n] between the number contained in the number 1.

 

Examples

E1

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

 

Problem-solving ideas

According LeetCode @ StefanPochmann algorithm, respectively, in the ones, tens, hundreds,. . . , Divided into two parts on the figures, and assuming that the number 1 position, and calculates the total number of possibilities Under this assumption, in sequence from low to high is calculated and added to obtain the final result.

For example, when n = 3141592, it is assumed m = 100, i.e. one hundred to one, then the n-divided into two parts, '3141' and '92', in one hundred is 1, a total front 0--3141 a total of 3142 kinds of possibilities, and after a total of 100 possibilities (Why not 92? because the one hundred original 5, that is, when one hundred still set to exceed its maximum position 1, and therefore the number of digits after the one hundred You are free).

But one thousand set to 1, i.e., when m = 1000, the final number can not simply by 1000 because the n already one thousand to one. Number 313, plus 592 to - so 0 needs to be calculated.

 

Complexity Analysis

Time complexity: O (N)

Space complexity: O (1)

 

Code

class Solution {
 public :
     int countDigitOne ( int n-) {
         int RES = 0 ;
         for ( Long  Long m = . 1 ; m <= n-; m * = 10 ) {
             // digital bits before for a, b for the after the number of bits 
            Long  Long a = n-/ m, B =% n- m;
             // (a +. 8) determines whether the current in order to avoid a median, and a subtraction operation 1 
            res + = ((a + . 8 ) / 10 ) * m + (A% 10 == . 1 ) * (B + . 1 ); 
        }
        
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/heyn1/p/11099463.html