[Programmers / JAVA] Level 1 Harshad Number (12947)
[Programmers / JAVA] Level 1 Harshad Number (12947)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
For a positive integer x to be a Harshad number, x must be divisible by the sum of its digits. For example, the digit sum of 18 is 1 + 8 = 9, and since 18 is evenly divisible by 9, 18 is a Harshad number. Complete the function solution that receives a natural number x and checks whether x is a Harshad number.
- x is an integer between 1 and 10000, inclusive.
| arr | return |
|---|---|
| 10 | true |
| 12 | true |
| 11 | false |
| 13 | false |
Example #1
The sum of all digits of 10 is 1. Since 10 is evenly divisible by 1, 10 is a Harshad number.
Example #2
The sum of all digits of 12 is 3. Since 12 is evenly divisible by 3, 12 is a Harshad number.
Example #3
The sum of all digits of 11 is 2. Since 11 is not evenly divisible by 2, 11 is not a Harshad number.
Example #4
The sum of all digits of 13 is 4. Since 13 is not evenly divisible by 4, 13 is not a Harshad number.
We need to determine a Harshad number. Compute the sum of all digits of an arbitrary number x, and check whether x is evenly divisible by this value. If it divides evenly, it's a Harshad number.
JAVA
/** * Harshad Number class * * @author RWB * @since 2021.12.13 Mon 21:52:12 */ class Solution { /** * Method that returns the answer * * @param x: [int] integer array * * @return [boolean] answer */ public boolean solution(int x) { int temp = x; int sum = 0; while (temp >= 10) { sum += temp % 10; temp /= 10; } sum += temp; return x % sum == 0; } }
