3099. Harshad Number
Problem Description
A Harshad number is an integer that is divisible by the sum of its digits.
Given an integer x
, you need to:
- Calculate the sum of all digits in
x
- Check if
x
is divisible by this sum - If
x
is divisible by the sum (meaningx
is a Harshad number), return the sum of digits - If
x
is not divisible by the sum (meaningx
is not a Harshad number), return-1
For example:
- If
x = 18
: The sum of digits is1 + 8 = 9
. Since18
is divisible by9
(18 ÷ 9 = 2), it's a Harshad number, so return9
. - If
x = 19
: The sum of digits is1 + 9 = 10
. Since19
is not divisible by10
, it's not a Harshad number, so return-1
.
The solution iterates through each digit of x
by repeatedly taking the remainder when divided by 10 (y % 10
) to get the last digit, adding it to the sum s
, then removing the last digit by integer division (y //= 10
). After calculating the sum of all digits, it checks if x % s == 0
to determine whether to return s
or -1
.
Intuition
The problem asks us to determine if a number is divisible by the sum of its digits. This naturally breaks down into two steps: first, we need to find the sum of the digits, and second, we need to check divisibility.
To extract digits from a number, we can use the mathematical property that the rightmost digit of any number can be obtained using the modulo operation % 10
. For instance, 123 % 10 = 3
gives us the last digit. After extracting a digit, we can remove it from the number using integer division // 10
, which shifts all digits one position to the right (essentially removing the last digit). For example, 123 // 10 = 12
.
By repeatedly applying these two operations in a loop, we can extract all digits one by one from right to left:
- Extract the last digit using
y % 10
- Add it to our running sum
- Remove the last digit using
y // 10
- Continue until no digits remain (when
y
becomes 0)
Once we have the sum of all digits, checking if the original number is a Harshad number is straightforward - we simply use the modulo operator again: if x % sum == 0
, then x
is evenly divisible by the sum of its digits.
The elegance of this approach lies in using basic arithmetic operations (%
and //
) to both decompose the number into its digits and verify the Harshad property, making it efficient with O(log n)
time complexity where n
is the number of digits.
Learn more about Math patterns.
Solution Approach
The solution uses a simulation approach to calculate the sum of digits and check the Harshad property.
We initialize two variables:
s = 0
: to store the sum of digitsy = x
: a copy of the input number to manipulate without losing the original value
The core algorithm uses a while loop that continues as long as y
has remaining digits (i.e., y > 0
):
while y: s += y % 10 # Extract and add the last digit to sum y //= 10 # Remove the last digit
Let's trace through an example with x = 123
:
- Initially:
s = 0
,y = 123
- First iteration:
s = 0 + (123 % 10) = 0 + 3 = 3
, theny = 123 // 10 = 12
- Second iteration:
s = 3 + (12 % 10) = 3 + 2 = 5
, theny = 12 // 10 = 1
- Third iteration:
s = 5 + (1 % 10) = 5 + 1 = 6
, theny = 1 // 10 = 0
- Loop ends since
y = 0
After calculating the sum s = 6
, we check if the original number is divisible by this sum:
return s if x % s == 0 else -1
For x = 123
and s = 6
: Since 123 % 6 = 3
(not zero), we return -1
.
The time complexity is O(log₁₀ x)
because the number of digits in x
is proportional to log₁₀ x
. The space complexity is O(1)
as we only use a constant amount of extra space for variables s
and y
.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with x = 12
:
Step 1: Initialize variables
s = 0
(to store sum of digits)y = 12
(copy of x to manipulate)
Step 2: Extract and sum digits
First iteration:
- Extract last digit:
y % 10 = 12 % 10 = 2
- Add to sum:
s = 0 + 2 = 2
- Remove last digit:
y = 12 // 10 = 1
Second iteration:
- Extract last digit:
y % 10 = 1 % 10 = 1
- Add to sum:
s = 2 + 1 = 3
- Remove last digit:
y = 1 // 10 = 0
Loop ends (y = 0)
Step 3: Check Harshad property
- Sum of digits:
s = 3
- Check divisibility:
12 % 3 = 0
- Since remainder is 0,
12
is divisible by3
Result: Return 3
(the sum of digits)
This confirms that 12 is a Harshad number because it's divisible by the sum of its digits (12 ÷ 3 = 4).
Solution Implementation
1class Solution:
2 def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
3 # Calculate the sum of digits of x
4 digit_sum = 0
5 temp_num = x
6
7 # Extract each digit and add to sum
8 while temp_num > 0:
9 digit_sum += temp_num % 10 # Get the last digit
10 temp_num //= 10 # Remove the last digit
11
12 # Check if x is divisible by the sum of its digits (Harshad number property)
13 # Return the digit sum if it's a Harshad number, otherwise return -1
14 return digit_sum if x % digit_sum == 0 else -1
15
1class Solution {
2 public int sumOfTheDigitsOfHarshadNumber(int x) {
3 // Calculate the sum of digits of x
4 int digitSum = 0;
5 int temp = x;
6
7 // Extract each digit and add to the sum
8 while (temp > 0) {
9 digitSum += temp % 10; // Get the last digit and add to sum
10 temp /= 10; // Remove the last digit
11 }
12
13 // Check if x is divisible by the sum of its digits (Harshad number property)
14 // If yes, return the digit sum; otherwise, return -1
15 return (x % digitSum == 0) ? digitSum : -1;
16 }
17}
18
1class Solution {
2public:
3 int sumOfTheDigitsOfHarshadNumber(int x) {
4 // Calculate the sum of all digits in the number
5 int digitSum = 0;
6
7 // Iterate through each digit by repeatedly dividing by 10
8 for (int temp = x; temp > 0; temp /= 10) {
9 // Extract the last digit using modulo operation and add to sum
10 digitSum += temp % 10;
11 }
12
13 // Check if x is divisible by the sum of its digits (Harshad number property)
14 // If yes, return the digit sum; otherwise, return -1
15 return (x % digitSum == 0) ? digitSum : -1;
16 }
17};
18
1/**
2 * Calculates the sum of digits of a Harshad number.
3 * A Harshad number is divisible by the sum of its digits.
4 *
5 * @param x - The input number to check
6 * @returns The sum of digits if x is a Harshad number, otherwise -1
7 */
8function sumOfTheDigitsOfHarshadNumber(x: number): number {
9 // Initialize sum of digits
10 let digitSum: number = 0;
11
12 // Extract and sum each digit by repeatedly dividing by 10
13 let tempNumber: number = x;
14 while (tempNumber > 0) {
15 // Add the last digit (remainder when divided by 10)
16 digitSum += tempNumber % 10;
17 // Remove the last digit by integer division
18 tempNumber = Math.floor(tempNumber / 10);
19 }
20
21 // Check if x is divisible by the sum of its digits
22 // If yes, it's a Harshad number - return the digit sum
23 // Otherwise, return -1
24 return x % digitSum === 0 ? digitSum : -1;
25}
26
Time and Space Complexity
The time complexity is O(log x)
, where x
is the input integer. This is because the while loop iterates through each digit of the number x
. The number of digits in x
is ⌊log₁₀(x)⌋ + 1
, which is proportional to log x
. In each iteration, we perform constant time operations (modulo, integer division, and addition).
The space complexity is O(1)
. The algorithm only uses a fixed amount of extra space for the variables s
and y
, regardless of the size of the input x
. No additional data structures that grow with the input size are used.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Division by Zero Error
The most critical pitfall in this solution is the potential for division by zero when checking x % digit_sum
. This occurs when the input x = 0
, resulting in digit_sum = 0
, which causes a ZeroDivisionError
when evaluating x % digit_sum
.
Solution: Add a special case check for zero:
def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
# Handle edge case: x = 0
if x == 0:
return 0 # 0 is considered a Harshad number (0 is divisible by 0)
digit_sum = 0
temp_num = x
while temp_num > 0:
digit_sum += temp_num % 10
temp_num //= 10
return digit_sum if x % digit_sum == 0 else -1
2. Modifying the Original Value
A common mistake is directly modifying x
instead of using a temporary variable:
# WRONG: This destroys the original value while x: digit_sum += x % 10 x //= 10 # Original x is now 0! # Can't check x % digit_sum anymore since x is 0
Solution: Always create a copy of the input for manipulation:
temp_num = x # Preserve original value while temp_num > 0: digit_sum += temp_num % 10 temp_num //= 10
3. Handling Negative Numbers
The problem doesn't explicitly state whether negative numbers are valid inputs. Using the modulo operator with negative numbers in Python can produce unexpected results.
Solution: Either work with the absolute value or add validation:
def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
# Option 1: Work with absolute value
abs_x = abs(x)
digit_sum = 0
temp_num = abs_x
while temp_num > 0:
digit_sum += temp_num % 10
temp_num //= 10
# Check divisibility with original number
return digit_sum if x % digit_sum == 0 else -1
4. Integer Overflow in Other Languages
While Python handles arbitrary precision integers, implementing this in languages like C++ or Java requires consideration of integer overflow for very large numbers.
Solution for other languages:
Use appropriate data types (like long long
in C++) or add overflow checks when necessary.
Which of the following is a good use case for backtracking?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!