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:
18
true
18
is a Harshad number because the sum of its digits is 1 + 8 = 9
, and 18
is divisible by 9
.19
false
19
is not a Harshad number because the sum of its digits is 1 + 9 = 10
, and 19
is not divisible by 10
.x
?
x
will be positive and within the typical range for standard integer operations in C++."true"
or "false"
)?
x
and compute the sum of its digits.x
is divisible by the sum of its digits.true
if x
is divisible by the sum of its digits, otherwise return false
.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;
}
x
, which takes O(log10(x))
time because we are repeatedly dividing the number by 10
.O(1)
since we are using a constant amount of extra space for variables.This code efficiently determines whether a given number is a Harshad number by leveraging basic arithmetic operations and digit extraction.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?