Harshad Number - Problem
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.
Input & Output
Example 1 — Basic Harshad Number
$
Input:
x = 18
›
Output:
9
💡 Note:
Sum of digits: 1 + 8 = 9. Since 18 % 9 = 0, 18 is divisible by 9, so return 9.
Example 2 — Not a Harshad Number
$
Input:
x = 23
›
Output:
-1
💡 Note:
Sum of digits: 2 + 3 = 5. Since 23 % 5 = 3 ≠ 0, 23 is not divisible by 5, so return -1.
Example 3 — Single Digit
$
Input:
x = 7
›
Output:
7
💡 Note:
Sum of digits: 7. Since 7 % 7 = 0, any single digit is always a Harshad number, so return 7.
Constraints
- 1 ≤ x ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given integer x
2
Process
Calculate digit sum and check divisibility
3
Output
Return digit sum or -1
Key Takeaway
🎯 Key Insight: A number is Harshad if it's divisible by the sum of its digits
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code