Neon Number
Problem
A neon number is a number whose square has a digit sum equal to the number. Example: 9 squared is 81 and 8 + 1 = 9. Read a non-negative integer and print true if it is a neon number, otherwise false.
Constraints
- 0 <= n <= 10^7
Examples
Input
9
Output
true
Input
8
Output
false
Solutions
We square the number and add the digits of the square with the same loop as the sum of digits. For the number 0 the square is 0 and the loop does not run, so the sum 0 is equal to the number.
/*
* Problem : Check if a number is a neon number.
* Input : One integer.
* Output : true or false.
* Approach: Add the digits of the square.
* Time : O(d)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method receives a number and returns true if the number is a neon number.
static boolean isNeon(long number) {
// Step 1: Negative numbers are not checked.
if (number < 0) {
return false;
}
// Step 2: Calculate the square of the number. Example: 9 * 9 = 81.
long square = number * number;
// Step 3: Add the digits of the square. The sum starts at 0.
long sum = 0;
while (square > 0) {
// Step 3a: Take the last digit and add it. Example: 81 % 10 = 1.
sum = sum + square % 10;
// Step 3b: Remove the last digit. Example: 81 / 10 = 8.
square = square / 10;
}
// Step 4: The number is neon if the digit sum is equal to the number.
return sum == number;
}
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
System.out.println(isNeon(number));
}
}
Hints (2)
- Which operator gives the last digit?
- Which operation removes the last digit?