首页 > 代码库 > LeetCode: Reverse Integer 解题报告

LeetCode: Reverse Integer 解题报告

Reverse Integer

Reverse digits of an integer.

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

click to show spoilers.

SOLUTION 1:

注意越界后返回0.先用long来计算,然后,把越界的处理掉。

public class Solution {    public int reverse(int x) {        long ret = 0;                while (x != 0) {            ret = ret * 10 + x % 10;            x /= 10;        }                if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {            return 0;        }                return (int)ret;    }}
View Code

 

GITHUB
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/math/Reverse.java

LeetCode: Reverse Integer 解题报告