题目
输入一个整数 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);
}
}