面试题43. 1~n 整数中 1 出现的次数

    技术2023-11-23  85

    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; } }
    Processed: 0.020, SQL: 9