您的位置:首页 > 其它

LeetCode Reverse Integer

2015-09-06 21:46 393 查看
题目:

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.
首先的一个问题就是如果碰到末尾是0结尾的,那么在反转过来后的数的开头就是0,那么这些个0就得去掉。
因为题目中给的数字是int类型的,而int是32位的数,例如1000000003,但是反转以后是3000000001,而这个数已经越界了,不在int的范围内了,所以这个问题得考虑,如何使得翻转过来的数不越界。考虑是用将翻转过来的是先取为long类型,然后再用类型的强制转换成int类型,如果考虑翻转过来的数大于Integer.MAX_VALUE或者是小雨Interger.MIN_VALUE,那么直接就取为0.

以下是我的代码:

public class Solution
{
   public static int reverse(int x)
   {
       String str = "";
       long sum = 0;
       boolean bool = false;
       if (x >= 0)
       {
           str = String.valueOf(x);
           StringBuilder strb = new StringBuilder();
           for (int i = str.length() - 1; i >= 0; i--) {
               strb.append(str.charAt(i));
           }
           str = strb.toString();
           //System.out.println(str);
           sum = Long.parseLong(str);
           if (sum > Integer.MAX_VALUE)
               return 0;
           else
               return (int) sum;
       }
       else
       {
           //x = Math.abs(x);
           //else if(x < 0)
           //x = x * -1;
           //System.out.println(x);
           str = String.valueOf(x);
           StringBuilder strb = new StringBuilder();
           for (int i = str.length() - 1; i >= 1; i--) {
               strb.append(str.charAt(i));
           }
           str = strb.toString();
           //System.out.println(str);
           sum = Long.parseLong(str);
           sum = -1 * sum;
           if (sum < Integer.MIN_VALUE)
               return 0;
           else
               return (int) sum;
       }
   }
}
中间可能有点繁琐,就是分别考虑了为非负数和负数的情况,其实可以考虑用一个标示来表示这个数是正数还是负数,然后每次只要考虑标示就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: