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
Convert number to tens, hundreds, thousands and so on - 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.
We can solve this problem by using a recursive approach.
Example
Following is the code −
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));
Output
This will produce the following output in console −
[ 100, 20, 3 ]
How It Works
The recursive function works by extracting the last digit using modulo operator (%), multiplying it by the appropriate place value factor, and then recursively processing the remaining digits:
- First call: 123 % 10 = 3, factor = 1, result = 3 * 1 = 3
- Second call: 12 % 10 = 2, factor = 10, result = 2 * 10 = 20
- Third call: 1 % 10 = 1, factor = 100, result = 1 * 100 = 100
Alternative Iterative Approach
Here's an iterative solution that achieves the same result:
const placeValueIterative = (num) => {
const result = [];
let factor = 1;
while (num > 0) {
const digit = num % 10;
if (digit !== 0) {
result.unshift(digit * factor);
}
num = Math.floor(num / 10);
factor *= 10;
}
return result;
};
console.log(placeValueIterative(12045));
[ 10000, 2000, 40, 5 ]
Conclusion
Both recursive and iterative approaches effectively break down numbers into their place values. The recursive method is more elegant, while the iterative approach may be easier to understand for beginners.
