Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Squared concatenation of a Number in JavaScript
We are required to write a JavaScript function that takes in a number and returns a new number in which all the digits of the original number are squared and concatenated.
For example: If the number is ?
99
Then the output should be ?
8181
because 9² is 81 and 9² is 81, so concatenating them gives 8181.
Example
Let's implement this function step by step:
const num = 9119;
const squared = num => {
const numStr = String(num);
let res = '';
for(let i = 0; i
Output
The output in the console will be ?
811181
How It Works
The function works by:
- Converting the number to a string to access individual digits
- Iterating through each character (digit)
- Converting each character back to a number using the unary plus operator (+)
- Calculating the square using Math.pow()
- Concatenating the squared result to the result string
Alternative Approach Using Array Methods
const squaredConcatenation = num => {
return String(num)
.split('')
.map(digit => Math.pow(+digit, 2))
.join('');
};
console.log(squaredConcatenation(123));
console.log(squaredConcatenation(999));
149 818181
Conclusion
Squared concatenation transforms each digit by squaring it and joining the results. Both the traditional loop and functional array methods produce the same result effectively.
Advertisements
