I was doing some coding challenges and encountered something I am not too familiar with. I am more curious to learn what it is and why it is there.
The prompt is pretty straightforward:
Given a 32-bit signed integer, reverse digits of an integer.
Example:
Input: -123
Output: -321
Example:
Input: 120
Output: 21
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
I came up with this.
var reverse = function(x) {
var isNegative = false;
if(x < 0){
isNegative = true;
x *= -1;
};
var reverseX = parseInt(String(x).split('').reverse((a,b) => a - b).join(''));
if(reverseX > Math.pow(2,32)){
return 0;
}
if(isNegative){
return -1 * reverseX
} else {
return reverseX;
}
};
However, I am stumped with some of the failing tests:
Input:
1563847412
Output:
2147483651
Expected: 0
To my understanding, 32 bit integer is 2^32. What is its significance in JS and what happen if I started going over? (2^32 + 1
)
My second question, if I may ask two, is I "anticipated" if value of reverseX
exceeds 2^32, but it is still failing the test.
if (reverseX > Math.pow(2, 32)) {
return 0;
}
How can I appropriately return 0
when I exceeded 32-bit integer?
question from:
https://stackoverflow.com/questions/47600096/what-is-32-bit-integer-in-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…