The Harshad Number interview question (also known as a Niven number) asks you to check if a given integer is divisible by the sum of its digits. If the number is divisible, you typically return the sum of the digits; otherwise, you return -1. For example, the number 18 is a Harshad number because , and 18 is divisible by 9.
Microsoft and other companies use this "Easy" level problem to assess a candidate's basic arithmetic fluency and their ability to implement simple mathematical rules. It tests the core skill of digit manipulation, which is a prerequisite for more complex string and number-based algorithms. It also evaluates attention to detail regarding return types and edge cases like zero or single-digit numbers.
This problem follows a simple Math interview pattern. The logic involves two steps:
number % 10) and then reduce the number using integer division (number / 10).Take the number 21:
Take the number 15:
sum % num instead of num % sum).str(n) in Python or n.toString() in JS to sum digits. While valid, it’s considered less "algorithmic" than the mathematical approach.Always master the "Digit Extraction" template: while num > 0: digit = num % 10; sum += digit; num //= 10;. This snippet is the foundation for dozens of coding problems. Being able to write it flawlessly in seconds shows your comfort with basic low-level logic.