A number is called a Harshad number (or Niven number) if it is divisible by the sum of its digits. Given a positive number num
, write a function to determine if the number is a Harshad number.
num
? Are we dealing with 32-bit integers only?
num
is a positive integer and fits within the 32-bit integer range.True
or False
)?
True
if num
is a Harshad number, otherwise False
.18
-> Output: True
(since 1 + 8 = 9 and 18 is divisible by 9)19
-> Output: False
(since 1 + 9 = 10 and 19 is not divisible by 10)True
if the number is divisible by the sum of its digits, otherwise return False
.def is_harshad_number(num):
# Step 1: Calculate the sum of digits
sum_of_digits = sum(int(digit) for digit in str(num))
# Step 2: Check if the number is divisible by the sum of its digits
return num % sum_of_digits == 0
# Test examples
print(is_harshad_number(18)) # True
print(is_harshad_number(19)) # False
print(is_harshad_number(21)) # True
print(is_harshad_number(1729)) # True
d
is the number of digits in the input number num
.
The provided solution is efficient given the constraints and should work well for numbers within the typical 32-bit integer range.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?