【LeetCode】7. Reverse Integer

来源:互联网 发布:乐动力没有数据 编辑:程序博客网 时间:2024/06/04 19:09

Reverse digits of an integer.

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

click to show spoilers.

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


思路:简单数字逆转问题,注意数据溢出的情况。

本题有个坑在数据为:-2147483648时,用x = -x 取反会失败,所以可以在判断是否溢出时,加绝对值


代码如下:

public class Solution {    public int reverse(int x) {        long ians = 0;        while(x != 0)        {            ians = ians * 10 + x % 10;            x /= 10;        }        if(Math.abs(ians) > Integer.MAX_VALUE)        {            return 0;        }        return (int)ians;    }}







原创粉丝点击