LeetCode 3099: Harshad Number Solution
Master LeetCode problem 3099 (Harshad Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3099. Harshad Number
Problem Explanation
Explanation
To solve this problem, we need to calculate the sum of the digits of the given number x. Then, we check if x is divisible by the sum of its digits. If it is divisible, we return the sum of the digits as the answer. Otherwise, we return -1.
Algorithm:
- Calculate the sum of digits of
x. - Check if
xis divisible by the sum of its digits. - Return the sum of digits if
xis a Harshad number, otherwise return -1.
Time Complexity: O(log(x)) - where x is the input number
Space Complexity: O(1)
Solution Code
class Solution {
public int sumOfDigits(int x) {
int sum = 0;
int num = x;
while (num > 0) {
sum += num % 10;
num /= 10;
}
if (x % sum == 0) {
return sum;
} else {
return -1;
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3099 (Harshad Number)?
This page provides optimized solutions for LeetCode problem 3099 (Harshad Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3099 (Harshad Number)?
The time complexity for LeetCode 3099 (Harshad Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3099 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3099 in Java, C++, or Python.