Check Number Neon in Java
Problem
A Neon number is a number where the sum of the digits of its own square equals the number itself.
Given a number, determine whether it is a Neon number.
Java Program
public class NeonNumberCheck {
public static void main(String[] args) {
int n = 9;
int square = n * n;
int digitSum = 0;
while (square > 0) {
digitSum += square % 10; // peel off the last digit of the square
square /= 10;
}
System.out.println(n + " is a Neon number: " + (digitSum == n));
}
}Output
Core Logic
Squaring the number first, then summing the digits of that square, checks the definition directly against the original number.
- 1
squareholdsn * n, computed once before the digit-summing loop runs. - 2A while loop peels off each digit of
squarewith% 10and/= 10, adding it intodigitSum. - 3Once every digit of the square has been summed,
digitSumis compared against the originaln.
9, the square is 81; summing its digits gives 8 + 1 = 9, which matches the original number.Key Point: Only single-digit numbers (and a couple of small exceptions) tend to satisfy this — squaring grows a number fast, so its digit sum rarely catches back up to the original value.
Why: The loop visits each digit of n's square once, where d is the square's digit count, and only a running total is kept.
Key Concepts
Approach 2: Java 8
public class NeonNumberCheckStream {
public static void main(String[] args) {
int n = 9;
int square = n * n;
// Streams each digit character, converts it to its digit value, and sums them
int digitSum = String.valueOf(square).chars()
.map(c -> c - '0')
.sum();
System.out.println(n + " is a Neon number: " + (digitSum == n));
}
}
Output
Core Logic
Streaming the square's digit characters and mapping each one to its numeric value sums the digits declaratively, without a manual while loop peeling off digits with modulo.
- 1
String.valueOf(square).chars()streams the square's digit characters as theirintcharacter codes. - 2
.map(c -> c - '0')converts each character code into its actual digit value. - 3
.sum()adds up every mapped digit into the final total. - 4That total is compared against the original
n, same as the manual version.
n = 9, the square 81's digit stream maps to 8 and 1, summing to 9, which matches.Key Point: chars() streams character codes, not digits directly — c - '0' is still needed inside map() to turn '8' (code 56) into the digit 8.
Why: The stream still visits each of the square's d digits once, and converting to a String first costs space proportional to d, unlike the manual loop's O(1) space.