Neon Number — Solution in Python, Java & C++
Neon Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at TCS and Wipro.
Neon Number is an easy coding problem on math, asked in TCS, Wipro and Mphasis interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: TCS, Wipro, Mphasis
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A neon number is a number whose square's digits add up to the number itself.
Given a non-negative integer n, return true if n is a neon number.
Example 1
Input: n = 9
Output: true
Explanation: 9² = 81 and 8 + 1 = 9.
Example 2
Input: n = 8
Output: false
Explanation: 8² = 64 and 6 + 4 = 10, not 8.
Example 3
Input: n = 1
Output: true
Explanation: 1² = 1.
Constraints
0 <= n <= 100000
Hints for Neon Number
Hint 1
Square the number, then sum the digits of the square.
Hint 2
Compare that digit sum with the original number.
Hint 3
In the range of an int there are only four neon numbers — 0, 1, 9 — so most inputs answer false.
How to solve Neon Number
Square the number, sum the digits of the square, and compare with the original.
Approach
- Compute
sq = n * n. - Peel the digits of
sqand add them up. - Return
total == n.
Why it works
The definition is literal. The digit sum of a 2k-digit square is at most 18k, which grows much slower than n, so only 0, 1 and 9 ever satisfy it.
Complexity
- Time —
O(log n) - Space —
O(1)
Pitfalls
0is neon (0² = 0), and the loop handles it because it runs zero times and the total is0.- Watch the square's width in fixed-width languages.
Reference solution
Python
def isNeon(n: int) -> bool:
sq = n * n
total = 0
while sq > 0:
total += sq % 10
sq //= 10
return total == nJava
public static boolean isNeon(int n) {
long sq = (long) n * n;
long total = 0;
while (sq > 0) {
total += sq % 10;
sq /= 10;
}
return total == n;
}C++
bool isNeon(int n) {
long long sq = (long long) n * n;
long long total = 0;
while (sq > 0) {
total += sq % 10;
sq /= 10;
}
return total == (long long) n;
}JavaScript
var isNeon = function(n) {
let sq = n * n, total = 0;
while (sq > 0) {
total += sq % 10;
sq = Math.floor(sq / 10);
}
return total === n;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.