Easy 0 solved 0% acceptance

Neon Number

Check whether the digit sum of a number's square equals the number.

What you'll learn

  • Square a number without overflow
  • Sum the digits of the square
  • Compare the result with the input

Problem

A neon number is a number whose square has a digit sum equal to the number itself. For example, 9² = 81 and 8 + 1 = 9, so 9 is a neon number.

Implement neon_number(n).

n² can reach 10^18, which fits in a signed 64-bit integer.

Input

n: The number to test.

Output

Return true if the sum of the decimal digits of n² equals n, otherwise false.

Constraints

0 ≤ n ≤ 10^9

Examples

Example 1
Input:
n = 9

Expected output:
expected = True
Input:
long long n = 9;

Expected output:
bool expected = true;
Input:
long n = 9;

Expected output:
bool expected = true;

Explanation

9² = 81 and 8 + 1 = 9, so the answer is true.

Example 2
Input:
n = 12

Expected output:
expected = False
Input:
long long n = 12;

Expected output:
bool expected = false;
Input:
long n = 12;

Expected output:
bool expected = false;

Explanation

12² = 144 and 1 + 4 + 4 = 9, which is not 12, so the answer is false.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Compute n × n in a 64-bit integer.

Hint 2

Add up the digits of the square with % 10 and / 10.

Hint 3

The digit sum of a square below 10^18 is at most 162, so large n can never be neon.

Expected complexity

O(d) time for d digits, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

The best passing solution of each coder. Faster, smaller and better-reviewed solutions rank higher.

No passing solutions yet. Solve it to take first place.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.