题目描述
这个比下面的快很多
样例
class Solution {
public int numberOf1Between1AndN_Solution(int n) {
int res=0;
int temp=1;
int ans=n;
while (ans!=0){
int yushu=ans%10;
ans=ans/10;
int item=n%temp;
if (yushu==0)
res+=ans*temp;
else if (yushu==1)
{
res+=(ans*temp+item+1);
}
else res+=(ans+1)*temp;
temp*=10;
}
return res;
}
}
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
java 代码
class Solution {
public int numberOf1Between1AndN_Solution(int n) {
String s = "" + n;
String[] item = s.split("");
int count = 0;
for (int i = 0; i < item.length; i++) {
if (i!=0)
count = count + Integer.valueOf(s.substring(0, i)) * (int) Math.pow(10, item.length - i - 1);
if (Integer.valueOf(item[i]) != 0) {
if (i==item.length-1)
count++;
else{
if (Integer.valueOf(item[i]) == 1){
StringBuilder sb2 = new StringBuilder(s.substring(i));
sb2.deleteCharAt(0);
count = count + Integer.valueOf(sb2.toString()) + 1;
}
else
count=count + (int) Math.pow(10, item.length - i - 1);
}
}
}
return count;
}
}