Do you need to "extract" each digit of a given number? Then this little TypeScript program is probably exactly what you're looking for. I have inserted some important comments about the "safe" input range, so make sure you are aware of it before using it in critical segments. There are many different solutions, this one avoids converting the number to a String internally, so it's a pure mathematical algorithm. (Note: I have updated the code to work correctly if given number is 0
.)
/**
* @param num A number in the int32 range [-2147483648 .. 2147483647]
* @returns A number[] containing each digit of `num`.
* If negative `num` given, resulting array will contain negatives numbers.
*/
function separateDigits(num: number): number[] {
let arr: number[] = [];
let lastDigit: number;
num = toInt32(num);
do {
lastDigit = num % 10;
arr.push(lastDigit);
// Updating num to num/10 cuts off the last digit:
num = toInt32(num / 10);
}
while (num !== 0);
return arr.reverse();
}
/**
* Fast bitwise operation, truncates floating point number resulting in int32.
* The >> bitwise operator is used, an overflow occurs if number too large.
* A *safe* integer division in JavaScript would be Math.floor(x/y);
* @param f A (JavaScript) number between [-2147483648.999 .. 2147483647.999]
* @returns Input 'f' truncated to Int32.
*/
function toInt32(f: number): number {
// Note that type "number" in JS is always "float" internally.
return f >> 0;
}
console.log(separateDigits(3142520));
// Output:
// [3, 4, 1, 2, 5, 2, 0]
Top comments (4)
>>>
): "Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.">>
): "The left operand will be converted to a 32-bit integer, which means floating point numbers will be truncated, and number not within the 32-bit bounds will over-/underflow."Thanks! I will update my code because right shift operators are more understandable to people coming from other languages. My solution using the ~~ operator seems to be very JS-specific :-/
Wouldnt it be easier to convert the number to a string and just split it? Performance-wise it doesnt make much difference.
benchmark: jsben.ch/67w9k
Thanks for the jsbench link, seems to be a very usefuly online tool, I will save that.
And about the different solution with toString conversion, yes, why not, if you prefer type conversion and the map method. They are definitely many solutions to the same problem.