【LeetCode】 7. Reverse Integer

来源:互联网 发布:建立客户档案软件 编辑:程序博客网 时间:2024/06/08 10:43

题目描述:

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.

假定输入为一个32位有符号整型,当反向整数溢出时,返回值一个为0

32位整数-2^31~2^31-1

 MAX_VALUE:2^31-1

MIN_VALUE -2^31

首先应该判断输入值是否小于MIN_VALUE,然后再进行反向操作,最后再判断是否溢出。

public class Solution {    public int reverse(int x) {        if(x <= Integer.MIN_VALUE){            return 0;        }        long result = 0;if(x < 0){return (-1)*reverse(Math.abs(x));}else{while(x !=0 ){result = result * 10 + x % 10;x /= 10;}}if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){return 0;}return (int)result;    }}