An integer divisible by the sum of its digits is said to be a Harshad number. You are given an integer x. Return the sum of the digits of __x
__ if __x __ is a Harshad number, otherwise, return __-1.
classSolution {
publicintsumOfTheDigitsOfHarshadNumber(int x) {
int s = 0, t = x;
while (t > 0) {
s += t % 10;
t /= 10;
}
return x % s == 0 ? s : -1;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funsumOfTheDigitsOfHarshadNumber(x: Int): Int {
var s = 0var t = x
while (t > 0) {
s += t % 10 t /=10 }
returnif (x % s ==0) s else -1 }
}
1
2
3
4
classSolution:
defsumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
s = sum(int(d) for d in str(x))
return s if x % s ==0else-1
1
2
3
4
5
6
7
8
9
10
11
12
structSolution;
impl Solution {
pubfnsum_of_the_digits_of_harshad_number(x: i32) -> i32 {
letmut s =0;
letmut t = x;
while t >0 {
s += t %10;
t /=10;
}
if x % s ==0 { s } else { -1 }
}
}