blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 Harshad Number (12947)

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.

[Programmers / JAVA] Level 1 Harshad Number (12947)

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.
RWB0104
@RWBwritten at 2021-12-18 12:48:00
Programmers

시리즈 모아보기

Programmers

60 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Harshad Number

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.
arrreturn
10true
12true
11false
13false

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;
	}
}
# Programmers# Algorithm# JAVA# Level 1
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08