topic description
Input an integer n, find the number of occurrences of 1 in the decimal representation of n integers from 1 to n.
For example, if you input 12, the integers from 1 to 12 include 1, 10, 11 and 12, and 1 appears 5 times in total.
train of thought
The way to get started is to convert the string, and then check each char violently. The code is posted below, 100% passed on Niuke, and time limit exceeded on Leetcode.
In the final analysis, it is a mathematical problem, and it is more reasonable to deal with it bit by bit.
Big guy idea:
Time complexity O(logn); space complexity O(1).
the code
1. Convert string
import java.util.ArrayList;
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
String str = null;
int count = 0;
for(int i=1; i<=n; i++){
str = String.valueOf(i);
char[] num_char = str.toCharArray();
for(int j=0; j<num_char.length;j++){
if(num_char[j] == '1'){
count++;
}
}
}
return count;
}
}
2. Find the law
class Solution {
public int countDigitOne(int n) {
int digit = 1, res = 0;
int high = n / 10, cur = n % 10, low = 0;
while(high != 0 || cur != 0) {
if(cur == 0) res += high * digit;
else if(cur == 1) res += high * digit + low + 1;
else res += (high + 1) * digit;
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return res;
}
}