




class Solution {
public int countDigitOne(int n) {
int ans = 0;
int digit = 1;
int high=n/10;
int low = 0;
int cur=n%10;
while(high!=0||cur!=0){
if(cur==0) ans+=digit*high;
else if(cur==1) ans+=high*digit+low+1;
else if(cur>1) ans+=(high+1)*digit;
low+=cur*digit;
digit*=10;
cur=high%10;
high/=10;
}
return ans;
}
}
本文介绍了一种高效算法,用于计算从1到n的所有整数中数字1出现的总次数。通过逐位分析,将问题分解为高位、当前位和低位三部分,实现了O(logn)的时间复杂度。
416

被折叠的 条评论
为什么被折叠?



