We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Harshad Number

Number: 3371

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an integer x, determine if it is a Harshad number. A Harshad number is an integer that is divisible by the sum of its digits. If x is a Harshad number, return the sum of the digits; otherwise, return -1.


Key Insights

  • Compute the sum of the digits of x.
  • Check if x is divisible by this sum.
  • With x between 1 and 100, digit extraction is straightforward and efficient.
  • Use simple arithmetic operations with a loop or string conversion.

Space and Time Complexity

Time Complexity: O(d), where d is the number of digits in x (d is constant for x ≤ 100, effectively O(1)). Space Complexity: O(1) since only a few integer variables are used.


Solution

The solution involves calculating the sum of the digits of x. This can be achieved by repeatedly taking the remainder when divided by 10 and reducing x until it becomes 0, or by converting x to a string and summing its characters as integers. After calculating the sum, we check if x % (sum of digits) equals 0. If yes, return the sum; otherwise, return -1.


Code Solutions

# Python solution
def harshadNumber(x: int) -> int:
    # Initialize the sum of digits to 0
    original = x
    sum_of_digits = 0
    # Loop to extract each digit
    while x > 0:
        digit = x % 10             # Get the last digit
        sum_of_digits += digit     # Add the digit to the sum
        x //= 10                   # Remove the last digit
    # Check divisibility: if original number is divisible by the sum of its digits
    if original % sum_of_digits == 0:
        return sum_of_digits       # Return the sum if it's a Harshad number
    else:
        return -1                  # Otherwise, return -1
        
# Example usage:
print(harshadNumber(18))  # Expected output: 9
print(harshadNumber(23))  # Expected output: -1
← Back to All Questions