Ticker

6/recent/ticker-posts

Leetcode-3099. Harshad Number


An integer divisible by the sum of its digits is said to be a Harshad number. You are given an integer x. Return the sum of the digits of x if x is a Harshad number, otherwise, return -1.

Example 1:

Input: x = 18

Output: 9

Explanation:

The sum of digits of x is 918 is divisible by 9. So 18 is a Harshad number and the answer is 9.

Example 2:

Input: x = 23

Output: -1

Explanation:

The sum of digits of x is 523 is not divisible by 5. So 23 is not a Harshad number and the answer is -1.

The provided solution solves the problem by checking if a given integer `x` is a Harshad number and returns the sum of its digits if it is, or `-1` if it isn't. A Harshad number is an integer that is divisible by the sum of its own digits. The solution starts by initializing a variable `sum` to store the sum of digits of `x`. It then iterates over the digits of `x` using a `while` loop. In each iteration, the last digit of `x` is extracted using the modulus operation (`x % 10`) and added to `sum`. After extracting the last digit, the number `x` is reduced by dividing it by 10 (`x = x / 10`), which effectively removes the last digit.

Once the sum of the digits is computed, the program checks if `x` is divisible by this sum using the condition `n % sum == 0`, where `n` is the original value of `x`. If `x` is divisible by the sum, the function returns the computed sum of the digits. If it is not divisible, the function returns `-1` to indicate that `x` is not a Harshad number.

For instance, in the case where `x = 18`, the sum of digits is `1 + 8 = 9`, and since `18 % 9 == 0`, the function returns `9`. In another example with `x = 23`, the sum of digits is `2 + 3 = 5`, and since `23 % 5 != 0`, the function returns `-1`.

The time complexity of the solution is O(d), where `d` is the number of digits in the number `x`, because the loop runs once for each digit to calculate the sum. The space complexity is O(1), as the solution only uses a constant amount of extra space for variables like `sum` and `n`. Overall, this approach is both time and space efficient for checking and handling Harshad numbers.

CODE:

class Solution {
public:
    int sumOfTheDigitsOfHarshadNumber(int x) {
        int sum=0;
        int n=x;
        while(x>0){
            sum+=x%10;
            x=x/10;
        }
        if(n%sum==0){
            return sum;
        }
        return -1;
    }
};

Also Read

Post a Comment

0 Comments