題目
輸入一個整數 n ,求1~n這n個整數的十進制表示中1出現的次數。
例如,輸入12,1~12這些整數中包含1 的數字有1、10、11和12,1一共出現了5次。
。
思路1: 暴力窮舉;
從n開始, 統計n包含的1的個數,再統計n-1, n-2…1,每一個數字包含的1的個數;求和即可
*時間: O(N^2) 在leetcode上會超時,在牛客網能通過~~
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
int count = 0;
for(int i = n; i > 0; i--){
for(int j = i; j>0; j /= 10){
if(j % 10 == 1) count++;
}
}
return count;
}
}
思路2: 遞歸
博主分享Java遞歸思路
- 時間複雜度 O(log10 n):
import java.lang.Math;
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
return f(n);
}
private int f(int n){
if(n <= 0) return 0;
String s = String.valueOf(n);
int high = s.charAt(0) - '0'; // 獲取高位的值;
int pow = (int)Math.pow(10, s.length()-1);
int last = n - high * pow;
if(high == 1) return f(pow-1) + last + 1 + f(last);
return pow + high*f(pow-1) + f(last);
}
}