Enter an integer n and find the number of occurrences of 1 in the decimal representation of n integers.
For example, if you enter 12, 1, and 12, the digits that contain 1 are 1, 10, 11, and 12. 1 appears five times.
Example 1:
Enter n =12Output:5
Copy the code
Example 2:
Enter n =13Output:6
Copy the code
Limitations:
1 <= n < 2^31
(cur) (cur) (d) (cur) (cur)
- The current bit is 0: the number of occurrences of 1 is the high * bit factor
- The current bit is 1: the number of occurrences of 1 is the high * bit factor + the low + 1
- Current bit >0: the number of occurrences of 1 is the high * bit factor + bit factor
class Solution {
public int countDigitOne(int n) {
// First initialize our bit information
int high = n/10;
int low = 0;
int cur = n%10;
int res = 0;
int d= 1;
If high==0 and cur==0, the loop ends
while(high ! =0|| cur ! =0) {if(cur == 0){
res += high*d;
}else if(cur == 1){
res += high*d + low +1;
}else{
res += high*d + d;
}
// Update bit information
low += cur * d;
cur = high % 10;
high = high / 10;
d = d * 10;
}
returnres; }}Copy the code