LeetCode记录之7——Reverse Integer

JAVA学习网 2017-09-03 09:28:01

Reverse digits of an integer.

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

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


反转数字的整数。

示例1:x = 123,返回321
示例2:x = -123,返回-321

注意:

假定输入为32位有符号整数。 当反转的整数溢出时,你的函数应该返回0。


  做LeetCode我个人最大的缺点就是上来就干,因为英语毕竟没有中文看着方便,导致好多提示根本没有注意。如本题溢出时返回0。


 

class Solution {
    public int reverse(int x) {
      boolean isAbove=true;
        StringBuffer sBuffer=new StringBuffer();
        int newX=x;
        if (x < 0) {
            isAbove = false;
            x = Math.abs(x);
        }
        while (x > 0) {
            sBuffer.append(x % 10);
            x = x / 10;
        }
        if (newX!=0) {
            try {
                if (isAbove)
                    return Integer.parseInt(sBuffer.toString());
                else
                    return -Integer.parseInt(sBuffer.toString());
            } catch (Exception e) {
                return 0;
            }
            
        }
        else 
            return 0;
    }
}

 

  顺道来复习下JAVA基本数据类型的数值范围:

byte的取值范围为-128~127,占用1个字节(-2的7次方到2的7次方-1) 
short的取值范围为-32768~32767,占用2个字节(-2的15次方到2的15次方-1) 
int的取值范围为(-2147483648~2147483647),占用4个字节(-2的31次方到2的31次方-1) 
long的取值范围为(-9223372036854774808~9223372036854774807),占用8个字节(-2的63次方到2的63次方-1)

  

 

 
阅读(750) 评论(0)