algoadvance

Leetcode 3099. Harshad Number

Problem Statement

Given a positive integer x, determine whether it is a Harshad number (also known as a Niven number). A Harshad number is an integer that is divisible by the sum of its digits. Implement a function in C++ that returns true if the given number x is a Harshad number, and false otherwise.

Example:

Clarifying Questions

  1. Range of Input: Is there a specific range for the input integer x?
    • Assumption: The integer x will be positive and within the typical range for standard integer operations in C++.
  2. Output Format: Should the function return a boolean value or a string ("true" or "false")?
    • Assumption: The function should return a boolean value.

Strategy

  1. Calculate Sum of Digits: Extract each digit of the given integer x and compute the sum of its digits.
  2. Check Divisibility: Check if x is divisible by the sum of its digits.
  3. Return Result: Return true if x is divisible by the sum of its digits, otherwise return false.

Code

Here is the implementation of the above strategy in C++:

#include <iostream>

bool isHarshadNumber(int x) {
    int sumOfDigits = 0;
    int originalNumber = x;
    
    // Calculate sum of digits
    while (x > 0) {
        sumOfDigits += x % 10;
        x /= 10;
    }
    
    // Check if the number is divisible by the sum of its digits
    return (originalNumber % sumOfDigits == 0);
}

int main() {
    int number = 18;
    std::cout << (isHarshadNumber(number) ? "true" : "false") << std::endl;
    number = 19;
    std::cout << (isHarshadNumber(number) ? "true" : "false") << std::endl;
    return 0;
}

Time Complexity

This code efficiently determines whether a given number is a Harshad number by leveraging basic arithmetic operations and digit extraction.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI