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
Harshad Number: Complete Process for x = 18Input18Digit Sum1 + 8 = 9Divisibility18 ÷ 9 = 2Output9Since 18 is evenly divisible by its digit sum (9), it is a Harshad number✓ Return the digit sum: 9
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
Asked in
Google 15 Microsoft 12 Apple 8
8.9K Views
Medium Frequency
~8 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen