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
Square every digit of a number - 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 ?
9119
Then the output should be ?
811181
because 9² is 81 and 1² is 1.
Example
Following is the code ?
const num = 9119;
const squared = num => {
const numStr = String(num);
let res = '';
for(let i = 0; i < numStr.length; i++){
const square = Math.pow(+numStr[i], 2);
res += square;
};
return res;
};
console.log(squared(num));
811181
Alternative Approach Using Array Methods
We can also solve this using array methods with a more functional approach:
const squareDigits = num => {
return String(num)
.split('')
.map(digit => Math.pow(+digit, 2))
.join('');
};
console.log(squareDigits(9119));
console.log(squareDigits(765));
console.log(squareDigits(0));
811181 493625 0
How It Works
The algorithm follows these steps:
- Convert the number to a string to access individual digits
- Iterate through each character (digit)
- Convert each digit back to number and square it using
Math.pow() - Concatenate all squared results into a final string
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| For Loop | Longer | Good | Faster |
| Array Methods | Shorter | Better | Slightly slower |
Conclusion
Both approaches effectively square each digit and concatenate the results. The array method approach is more concise and functional, while the for loop provides better performance for large numbers.
Advertisements
