Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Harshad Number

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3099" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 9. 18 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 5. 23 is not divisible by 5. So 23 is not a Harshad number and the answer is -1. Constraints: 1 <= x <= 100

Explanation

Here's a breakdown of the solution:

  • Calculate Digit Sum: Iterate through the digits of the input number x and compute their sum.
  • Harshad Number Check: Verify if the original number x is divisible by the calculated digit sum.
  • Return Value: If divisible, return the digit sum; otherwise, return -1.

  • Runtime Complexity: O(log x) (due to digit extraction), Storage Complexity: O(1)

Code

    def solve():
    x = int(input())

    sum_digits = 0
    temp = x
    while temp > 0:
        sum_digits += temp % 10
        temp //= 10

    if sum_digits == 0:
      print(-1)
      return

    if x % sum_digits == 0:
        print(sum_digits)
    else:
        print(-1)

solve()

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Harshad Number