A Neon Number is a number whose square has a digit sum equal to the number itself. Given a number num, the task is to check whether it is a Neon Number and return true if the condition is satisfied; otherwise, return false.
Examples
Input: num = 9
Output: true
Explanation: square of 9 is 9 * 9 = 81 , sum of digit of square is 8 + 1 = 9 (i.e equal to given number).Input: num = 10
Output: false
Explanation: Square of 10 is 10 * 10 = 100 , sum of digit of square is 1 + 0 + 0 = 1 (i.e. not equal to given number).
Approach
The approach is to calculate the square of the number, find the sum of its digits, and compare the sum with the original number.
- Calculate the square of the given number.
- Extract each digit of the square using % 10.
- Add the extracted digits to sum.
- Compare sum with the original number.
- Return true if both values are equal; otherwise, return false.
#include <stdio.h>
// Checks whether a number is a Neon Number
int isNeon(int num)
{
// Calculate the square of the number
int square = num * num;
// Store the square for digit extraction
int n = square;
// Store the sum of digits
int sum = 0;
// Extract and add each digit of the square
while (n != 0) {
int digit = n % 10;
sum += digit;
n /= 10;
}
// Check whether the digit sum equals the original number
return sum == num;
}
int main()
{
int num = 9;
// Check whether the number is Neon
if (isNeon(num))
printf("true");
else
printf("false");
return 0;
}
Output
true
Explanation
- square stores the square of the given number.
- The while loop extracts each digit using % 10 and adds it to sum.
- n /= 10 removes the last digit after each iteration.
- The function returns 1 when sum equals num; otherwise, it returns 0.