Problem Description
Given an integer x, determine if it is a Harshad number. A Harshad number is an integer that is divisible by the sum of its digits. If x is a Harshad number, return the sum of the digits; otherwise, return -1.
Key Insights
- Compute the sum of the digits of x.
- Check if x is divisible by this sum.
- With x between 1 and 100, digit extraction is straightforward and efficient.
- Use simple arithmetic operations with a loop or string conversion.
Space and Time Complexity
Time Complexity: O(d), where d is the number of digits in x (d is constant for x ≤ 100, effectively O(1)). Space Complexity: O(1) since only a few integer variables are used.
Solution
The solution involves calculating the sum of the digits of x. This can be achieved by repeatedly taking the remainder when divided by 10 and reducing x until it becomes 0, or by converting x to a string and summing its characters as integers. After calculating the sum, we check if x % (sum of digits) equals 0. If yes, return the sum; otherwise, return -1.