classSolution {
public:int countDigitOne(int n) {
int res =0;
for (longlong m =1; m <= n; m *=10) {
int a = n / m, b = n % m;
res += (a +8) /10* m + (a %10==1? b +1:0);
}
return res;
}
};
1
2
3
4
5
6
7
8
9
funccountDigitOne(nint) int {
res:=0form:=1; m<=n; m*=10 {
a, b:=n/m, n%mres+= (a+8)/10*mifa%10==1 { res+=b+1 }
}
returnres}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintcountDigitOne(int n) {
int res = 0;
for (long m = 1; m <= n; m *= 10) {
long a = n / m, b = n % m;
res += (a + 8) / 10 * m + (a % 10 == 1 ? b + 1 : 0);
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funcountDigitOne(n: Int): Int {
var res = 0var m = 1Lwhile (m <= n) {
val a = n / m
val b = n % m
res += ((a + 8) / 10 * m).toInt() + if (a % 10==1) (b + 1).toInt() else0 m *=10 }
return res
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defcountDigitOne(self, n: int) -> int:
res, m =0, 1while m <= n:
a, b = n // m, n % m
res += (a +8) //10* m
if a %10==1:
res += b +1 m *=10return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfncount_digit_one(n: i32) -> i32 {
letmut res =0;
letmut m =1;
while m <= n {
let a = n / m;
let b = n % m;
res += (a +8) /10* m;
if a %10==1 { res += b +1; }
m *=10;
}
res
}
}