码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Reverse Integer

时间:2014-07-18 09:34:59      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   strong   

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

这道题出的挺好,但是对答案的处理非常不好,tip中显式的声明了溢出该怎么办,但是case中并未给出处理,说白了,case中压根就没有给出可能溢出的case。因此下面的代码可以过

bubuko.com,布布扣
 1 public class Solution {
 2     public int reverse(int x) {
 3         boolean isPositive = x > 0?true:false;
 4         int tem = Math.abs(x);
 5         int result = 0;
 6         while(tem!=0){
 7             int temp = tem % 10;
 8             tem /= 10;
 9             result = 10 * result + temp;
10         }
11         return isPositive?result:-result;
12     }
13 }
View Code

 

当然上面的代码,虽然过了,但是藏有很大的bug,下面这段代码对上面可能溢出的情况做出了处理,当返回结果溢出时,返回Integer.MAX_VALUE或者Integer.MIN_VALUE

 1 public class Solution {
 2   public int reverse(int x) {
 3         int result = 0;
 4         boolean isNegative = x < 0 ? true : false; 
 5         int n = Math.abs(x);
 6         while(n!=0){
 7             int temp = n % 10;
 8             n /= 10;
 9             if(!isOverFlow(result, temp, isNegative) ){
10                 result = 10 * result + temp;
11             }else{
12                 result = !isNegative ? Integer.MAX_VALUE:Integer.MIN_VALUE;
13             }
14         }
15         return isNegative ? -result : result;
16     }
17     private boolean isOverFlow(int num,int tem, boolean isNegative){
18         if(!isNegative){
19             //Integer.MAX_VALUE = 2147483647
20             if( (Integer.MAX_VALUE - tem) / 10 < num ) return true;
21             return false;
22         }else{
23             //Integer.MIN_VALUE = -2147483648
24             if( (Integer.MIN_VALUE + tem) / 10 > -num ) return true;
25             return false;
26         }
27     }
28 }

FYI

 

 

 

[leetcode]Reverse Integer,布布扣,bubuko.com

[leetcode]Reverse Integer

标签:des   style   blog   http   color   strong   

原文地址:http://www.cnblogs.com/huntfor/p/3851988.html

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