Harshad Number — Solution in Python, Java & C++
Harshad Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at TCS and Infosys.
Harshad Number is an easy coding problem on math, asked in TCS, Infosys and Mindtree interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: TCS, Infosys, Mindtree
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A Harshad number (or Niven number) is an integer that is divisible by the sum of its own digits.
Given a positive integer n, return true if n is a Harshad number.
Example 1
Input: n = 18
Output: true
Explanation: 1 + 8 = 9 and 18 is divisible by 9.
Example 2
Input: n = 19
Output: false
Explanation: 1 + 9 = 10 and 19 is not divisible by 10.
Example 3
Input: n = 1729
Output: true
Explanation: 1 + 7 + 2 + 9 = 19 and 1729 = 19 × 91.
Constraints
1 <= n <= 1000000
Hints for Harshad Number
Hint 1
Sum the digits, then take one modulo.
Hint 2
Because
n >= 1, the digit sum is at least 1 and can never be zero — no divide-by-zero guard needed.Hint 3
Every single-digit number is Harshad.
How to solve Harshad Number
Sum the digits and test whether the number is divisible by that sum.
Approach
- Accumulate the digits of
nwith% 10/// 10. - Return
n % total == 0.
Why it works
The definition is direct. Because n >= 1, at least one digit is non-zero and the divisor is never zero.
Complexity
- Time —
O(d) - Space —
O(1)
Pitfalls
- Every single-digit number is Harshad —
n % n == 0. - If the constraints ever allowed
0, the digit sum would be zero and a guard would be needed.
Reference solution
Python
def isHarshad(n: int) -> bool:
total, x = 0, n
while x > 0:
total += x % 10
x //= 10
return n % total == 0Java
public static boolean isHarshad(int n) {
int total = 0;
int x = n;
while (x > 0) {
total += x % 10;
x /= 10;
}
return n % total == 0;
}C++
bool isHarshad(int n) {
int total = 0;
int x = n;
while (x > 0) {
total += x % 10;
x /= 10;
}
return n % total == 0;
}JavaScript
var isHarshad = function(n) {
let total = 0, x = n;
while (x > 0) {
total += x % 10;
x = Math.floor(x / 10);
}
return n % total === 0;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.