码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Reverse Integer

时间:2015-08-29 23:04:29      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:

Reverse Integer 

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

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 };

 

 

 

 

 

[LeetCode][JavaScript]Reverse Integer

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4769970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!