Check Number Harshad in Java
Problem
A Harshad number (also called a Niven number) is a number that is evenly divisible by the sum of its own digits.
Given a number, determine whether it is a Harshad number.
Java Program
public class HarshadNumberCheck {
public static void main(String[] args) {
int n = 18;
int original = n;
int digitSum = 0;
while (n > 0) {
digitSum += n % 10; // peel off the last digit
n /= 10;
}
boolean isHarshad = original % digitSum == 0;
System.out.println(original + " is a Harshad number: " + isHarshad);
}
}Output
Core Logic
Summing the digits first, then checking whether that sum evenly divides the original number, tests the definition directly.
- 1A while loop peels off each digit of
nwithn % 10, adding it intodigitSum, whilen /= 10removes it. - 2The original value is kept in
originalbefore the loop consumesn. - 3Once every digit has been summed,
original % digitSum == 0checks whether the digit sum divides the number evenly.
18, the digit sum is 1 + 8 = 9, and 18 % 9 == 0, so it's reported as a Harshad number.Key Point: Every single-digit number is trivially a Harshad number, since a number always divides evenly by itself — the digit sum only becomes interesting once a number has two or more digits.
Why: The loop runs once per digit to build the sum, and only a couple of integer variables are kept regardless of how large n is.
Key Concepts
Approach 2: Java 8
public class HarshadNumberCheckStream {
public static void main(String[] args) {
int n = 18;
// Maps each digit character to its numeric value and sums them
int digitSum = String.valueOf(n).chars().map(c -> c - '0').sum();
boolean isHarshad = n % digitSum == 0;
System.out.println(n + " is a Harshad number: " + isHarshad);
}
}
Output
Core Logic
The same digit sum can be produced by mapping each character of the number's string form to its numeric value and reducing the stream to a total.
- 1
String.valueOf(n).chars()returns anIntStreamof the number's digit characters. - 2
.map(c -> c - '0')converts each character code to its actual digit value using ASCII arithmetic. - 3
.sum()reduces the stream of digits down to a single total, the same digit sum the loop computes.
18, the stream maps '1' and '8' to 1 and 8, summing to 9, the same digit sum as the loop version.Key Point: This expresses the exact same digit-summing logic as a stream pipeline instead of a manual loop — the divisibility check afterward is unchanged.
Why: The stream still visits each digit once to build the sum, and holds no more than a running total.