Input: num =30Output: 14Explanation:
The 14 integers less than or equal to 30 whose digit sums are even are
2,4,6,8,11,13,15,17,19,20,22,24,26, and 28.
classSolution {
public:int countEven(int num) {
int ans =0;
for (int x =1; x <= num; ++x) {
int s =0, t = x;
while (t) { s += t %10; t /=10; }
if (s %2==0) ans++;
}
return ans;
}
};
classSolution {
publicintcountEven(int num) {
int ans = 0;
for (int x = 1; x <= num; x++) {
int s = 0, t = x;
while (t > 0) { s += t % 10; t /= 10; }
if (s % 2 == 0) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funcountEven(num: Int): Int {
var ans = 0for (x in1..num) {
var s = 0var t = x
while (t > 0) {
s += t % 10 t /=10 }
if (s % 2==0) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defcountEven(self, num: int) -> int:
ans =0for x in range(1, num +1):
s = sum(int(d) for d in str(x))
if s %2==0:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfncount_even(num: i32) -> i32 {
letmut ans =0;
for x in1..=num {
letmut s =0;
letmut t = x;
while t >0 {
s += t %10;
t /=10;
}
if s %2==0 {
ans +=1;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
countEven(num: number):number {
letans=0;
for (letx=1; x<=num; x++) {
lets=0, t=x;
while (t>0) {
s+=t%10;
t= Math.floor(t/10);
}
if (s%2===0) ans++;
}
returnans;
}
}