[LeetCode] Harshad Number

3099. Harshad Number

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
int helper(int x) {
int res = 0;
while(x) {
res += x % 10;
x /= 10;
}
return res;
}
public:
int sumOfTheDigitsOfHarshadNumber(int x) {
int sum = helper(x);
if(x % sum == 0) return sum;
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/31/PS/LeetCode/harshad-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.