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?

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).

注意0的处理,如果不单独拿出来 则会输出null。。。 

 1     public int reverse(int x) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         if(x == 0){
 5             return 0;
 6         }
 7         StringBuffer s = new StringBuffer();
 8         StringBuffer b = new StringBuffer(Integer.toString(x));
 9         if(b.charAt(0) == '-'){
10             s.append('-');
11             b.deleteCharAt(0);
12         }
13         int cur;
14         int flag = 0;
15         for(int xx = b.length() - 1; xx > -1 ; xx --){
16             if(flag == 0 && b.charAt(xx) == '0'){
17             }
18             else{
19                 flag = 1;
20                 s.append(b.charAt(xx));
21             }
22         }
23         return Integer.valueOf(s.toString());
24         
25     }

 第二遍:

不使用复杂的数据结构。

 1 public class Solution {
 2     public int reverse(int x) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int sig = 1;
 6         int result = 0;
 7         if(x == 0){
 8             return 0;
 9         }else if(x < 0){
10             sig = -1;
11             x= -x;
12         }
13         for(; x > 0; x /= 10){
14             result = result * 10 + x % 10;
15         }
16         return result * sig;
17     }
18 }

 第三遍:

 1 public class Solution {
 2     public int reverse(int x) {
 3         int sig = x > 0 ? 1 : -1;
 4         x *= sig;
 5         int result = 0;
 6         for( ; x > 0; x /= 10){
 7             if(result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && x % 10 > Integer.MAX_VALUE % 10)) return -1;
 8             result = result * 10 + x % 10;
 9         }
10         return sig * result;
11     }
12 }

 

posted on 2013-04-16 04:15  Step-BY-Step  阅读(226)  评论(0编辑  收藏  举报

导航