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

LeetCode记录之——Reverse Integer

时间:2017-09-02 16:53:16      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:isa   32位   des   sig   byte   leetcode   reverse   put   func   

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)

  

 

 

LeetCode记录之——Reverse Integer

标签:isa   32位   des   sig   byte   leetcode   reverse   put   func   

原文地址:http://www.cnblogs.com/vincentme/p/7466809.html

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