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 - String-Based Digit Sum INPUT 18 x = 18 Convert to String: '1' '8' , index 0 index 1 Input Value: x = 18 ALGORITHM STEPS 1 Convert to String str(18) = "18" 2 Sum Digits 1 + 8 = 9 3 Check Divisibility 18 % 9 == 0 ? 4 Return Result If yes: sum, else: -1 Calculation: digit_sum = 1 + 8 = 9 18 % 9 = 0 0 == 0 --> TRUE FINAL RESULT Is 18 a Harshad Number? YES! 18 is divisible by sum of its digits (9) 18 / 9 = 2 Output: 9 Return digit sum = 9 OK - Valid Key Insight: A Harshad number (also called Niven number) is divisible by the sum of its digits. Using string conversion makes digit extraction simple: iterate through each character and sum. Time Complexity: O(d) where d = number of digits | Space Complexity: O(d) for string TutorialsPoint - Harshad Number | String-Based Digit Sum Approach
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