Horje
JavaScript Program to Check whether the Input Number is a Neon Number

A neon number is a number where the sum of digits of its square equals the number itself. For example, 9 is a neon number because 9^2 = 81, and the sum of the digits 81 is 9. There are several ways to check if a given number is a neon number in JavaScript or not which are as follows:

Using naive method

The most straightforward way to check if a number is a neon number is to square the number, calculate the sum of the digits of the square, and then compare the sum to the original number.

Example: To check whether a number is neon or not using a naive approach.

Javascript

function isNeonNumber(num) {
  let square = num * num;
  let sumOfDigits = 0;
 
  while (square > 0) {
    sumOfDigits += square % 10;
    square = Math.floor(square / 10);
  }
 
  return sumOfDigits === num;
}
 
console.log(isNeonNumber(9));
console.log(isNeonNumber(8));

Output

true
false

Using string conversion

Another way to approach this problem is to convert the square of the number to a string and then iterate through the characters of the string to calculate the sum of the digits.

Example: To demonstrate checking the number whether it is one number or not by converting it into a string and iterating over it.

Javascript

function isNeonNumber(num) {
  let square = (num * num).toString();
  let sumOfDigits = 0;
 
  for (let digit of square) {
    sumOfDigits += parseInt(digit, 10);
  }
 
  return sumOfDigits === num;
}
 
console.log(isNeonNumber(9));
console.log(isNeonNumber(8));

Output

true
false

Using array methods

We can also use JavaScript array methods to make the code more concise. In this approach, we convert the square of the number to a string, split the string into an array of characters, and then use the reduce method to calculate the sum of the digits.

Example: To demonstrate checking whether the numbers are neon numbers or not using array methods.

Javascript

function isNeonNumber(num) {
  let sumOfDigits = (num * num)
    .toString()
    .split("")
    .reduce((sum, digit) => {
      return sum + parseInt(digit, 10);
    }, 0);
 
  return sumOfDigits === num;
}
 
console.log(isNeonNumber(9));
console.log(isNeonNumber(5));

Output

true
false



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
$ in JavaScript $ in JavaScript
How to Sort Objects in an Array Based on a Property in a Specific Order in TypeScript ? How to Sort Objects in an Array Based on a Property in a Specific Order in TypeScript ?
How to Define Generic Type for Matching Object Property Types in TypeScript ? How to Define Generic Type for Matching Object Property Types in TypeScript ?
How to Convert an Array of Objects into an Array of Arrays ? How to Convert an Array of Objects into an Array of Arrays ?
Random Choice Picker using HTML CSS and JavaScript Random Choice Picker using HTML CSS and JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14