[LeetCode][JavaScript]Reverse Integer
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
https://leetcode.com/problems/reverse-integer/
倒转数字,超过了2^31返回0。
1 /** 2 * @param {number} x 3 * @return {number} 4 */ 5 var reverse = function(x) { 6 var sign = 1, res = 0, base = 1; 7 if(x < 0){ 8 sign = -1; 9 x = -1 * x; 10 } 11 x = x + ""; 12 for(var i = 0; i < x.length; i++){ 13 res += base * parseInt(x[i]); 14 base *= 10; 15 } 16 if(res > Math.pow(2,31)){ 17 return 0; 18 } 19 return sign * res; 20 };