3099. Harshad Number
Description
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
.
Example 1:
Input: x = 18
Output: 9
Explanation:
The sum of digits of x
is 9
. 18
is divisible by 9
. So 18
is a Harshad number and the answer is 9
.
Example 2:
Input: x = 23
Output: -1
Explanation:
The sum of digits of x
is 5
. 23
is not divisible by 5
. So 23
is not a Harshad number and the answer is -1
.
Constraints:
1 <= x <= 100
Solutions
Solution 1: Simulation
We can calculate the sum of the digits of $x$, denoted as $s$, by simulation. If $x$ can be divided evenly by $s$, then we return $s$, otherwise, we return $-1$.
The time complexity is $O(\log x)$, where $x$ is the input integer. The space complexity is $O(1)$.
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 |
|