Leetcode 3099: Harshad Number

grid47
grid47
Exploring patterns and algorithms
Jan 2, 2024 4 min read

An integer is called a Harshad number if it is divisible by the sum of its digits. You are given an integer x. Your task is to return the sum of the digits of x if x is a Harshad number. Otherwise, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of a single integer `x` where `1 <= x <= 100`.
Example: x = 36
Constraints:
• 1 <= x <= 100
Output: Return the sum of the digits of `x` if `x` is a Harshad number. Otherwise, return -1.
Example: Output: 9
Constraints:
Goal: To determine if the number is divisible by the sum of its digits and return the appropriate result.
Steps:
• Calculate the sum of the digits of the number `x`.
• Check if `x` is divisible by this sum.
• If divisible, return the sum of the digits. Otherwise, return -1.
Goal: The integer `x` must be between 1 and 100 inclusive.
Steps:
• 1 <= x <= 100
Assumptions:
• The input will always be a positive integer less than or equal to 100.
Input: x = 36
Explanation: The sum of the digits of `x` is `9`, and since `36` is divisible by `9`, the result is `9`.

Input: x = 25
Explanation: The sum of the digits of `x` is `7`, and since `25` is not divisible by `7`, the result is `-1`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus