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
Finding place value of a number in JavaScript
In JavaScript, finding the place value of digits means extracting each digit's positional worth. For example, in the number 1234, the place values are [1000, 200, 30, 4].
We need to write a function that takes a positive integer and returns an array with the place values of all digits.
Problem Example
If the input number is:
const num = 1234;
Then the output should be:
[1000, 200, 30, 4]
Using Recursive Approach
This problem is well-suited for recursion since we need to process each digit and calculate its place value based on position.
const splitNumber = (num, arr = [], m = 1) => {
if(num){
return splitNumber(Math.floor(num / 10), [m * (num % 10)].concat(arr), m * 10);
}
return arr;
};
console.log(splitNumber(2346));
console.log(splitNumber(5664));
console.log(splitNumber(3453));
console.log(splitNumber(2));
console.log(splitNumber(657576));
console.log(splitNumber(345232));
[ 2000, 300, 40, 6 ] [ 5000, 600, 60, 4 ] [ 3000, 400, 50, 3 ] [ 2 ] [ 600000, 50000, 7000, 500, 70, 6 ] [ 300000, 40000, 5000, 200, 30, 2 ]
Using Iterative Approach
Here's an alternative iterative solution that's easier to understand:
const splitNumberIterative = (num) => {
const result = [];
let multiplier = 1;
// Find the highest place value
let temp = num;
while (temp >= 10) {
multiplier *= 10;
temp = Math.floor(temp / 10);
}
// Extract place values from left to right
while (multiplier >= 1) {
const digit = Math.floor(num / multiplier);
result.push(digit * multiplier);
num = num % multiplier;
multiplier = Math.floor(multiplier / 10);
}
return result;
};
console.log(splitNumberIterative(1234));
console.log(splitNumberIterative(5678));
[ 1000, 200, 30, 4 ] [ 5000, 600, 70, 8 ]
How the Recursive Solution Works
The recursive function works by:
- num % 10 - Gets the rightmost digit
- Math.floor(num / 10) - Removes the rightmost digit
- m - Tracks the current place value multiplier (1, 10, 100, etc.)
- arr - Accumulates the place values from right to left
Comparison
| Approach | Complexity | Readability | Memory Usage |
|---|---|---|---|
| Recursive | O(d) time, O(d) space | Concise but complex | Higher (call stack) |
| Iterative | O(d) time, O(1) space | More explicit | Lower |
Conclusion
Both recursive and iterative approaches effectively extract place values from numbers. The recursive solution is more concise, while the iterative version is more readable and memory-efficient.
