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
Expanding Numerals in JavaScript
We are required to write a function that, given a number, say, 123, will output an array ?
[100, 20, 3]
Basically, the function is expected to return an array that contains the place value of all the digits present in the number taken as an argument by the function.
Understanding Place Values
Each digit in a number has a place value based on its position. For example, in 123:
- 1 is in the hundreds place (1 × 100 = 100)
- 2 is in the tens place (2 × 10 = 20)
- 3 is in the units place (3 × 1 = 3)
Using Recursive Approach
We can solve this problem by using a recursive approach that processes digits from right to left:
const num = 123;
const placeValue = (num, res = [], factor = 1) => {
if(num){
const val = (num % 10) * factor;
res.unshift(val);
return placeValue(Math.floor(num / 10), res, factor * 10);
};
return res;
};
console.log(placeValue(num));
[ 100, 20, 3 ]
How It Works
The recursive function works as follows:
- Extract the last digit using
num % 10 - Multiply it by the current factor (1, 10, 100, etc.)
- Add the result to the beginning of the array using
unshift() - Remove the last digit using
Math.floor(num / 10) - Increase the factor by 10 and repeat
Alternative Iterative Approach
Here's a non-recursive solution using string manipulation:
const expandNumber = (num) => {
const str = num.toString();
const result = [];
for(let i = 0; i 0) {
result.push(placeValue);
}
}
return result;
};
console.log(expandNumber(123));
console.log(expandNumber(1024));
[ 100, 20, 3 ] [ 1000, 20, 4 ]
Handling Edge Cases
Let's test with numbers containing zeros:
const placeValue = (num, res = [], factor = 1) => {
if(num){
const val = (num % 10) * factor;
if(val > 0) { // Only add non-zero values
res.unshift(val);
}
return placeValue(Math.floor(num / 10), res, factor * 10);
};
return res;
};
console.log(placeValue(1005));
console.log(placeValue(200));
[ 1000, 5 ] [ 200 ]
Conclusion
Expanding numerals breaks down numbers into their place values. The recursive approach processes digits efficiently, while filtering out zeros gives cleaner results for practical use.
