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
Expressing numbers in expanded form - JavaScript
Suppose we are given a number 124 and are required to write a function that takes this number as input and returns its expanded form as a string.
The expanded form of 124 is ?
'100+20+4'
How It Works
The algorithm converts each digit to its place value by multiplying it with the appropriate power of 10, then joins non-zero values with '+' signs.
Example
Following is the code ?
const num = 125;
const expandedForm = num => {
const numStr = String(num);
let res = '';
for(let i = 0; i < numStr.length; i++){
const placeValue = +(numStr[i]) * Math.pow(10, (numStr.length - 1 - i));
if(numStr.length - i > 1){
res += `${placeValue}+`
}else{
res += placeValue;
};
};
return res;
};
console.log(expandedForm(num));
Output
Following is the output in the console ?
100+20+5
Improved Version
Here's a cleaner approach that filters out zero values and uses array methods:
const expandedFormImproved = num => {
return String(num)
.split('')
.map((digit, index, arr) => {
const placeValue = digit * Math.pow(10, arr.length - 1 - index);
return placeValue;
})
.filter(value => value > 0)
.join('+');
};
console.log(expandedFormImproved(125));
console.log(expandedFormImproved(102)); // Handles zeros
console.log(expandedFormImproved(7)); // Single digit
100+20+5 100+2 7
Comparison
| Approach | Handles Zeros | Code Length | Readability |
|---|---|---|---|
| Original Loop | No | Longer | Good |
| Array Methods | Yes | Shorter | Better |
Conclusion
Both approaches work for basic cases, but the improved version handles edge cases like zeros and uses modern JavaScript array methods for cleaner, more readable code.
Advertisements
