首页 > 代码库 > [LeetCode]Reverse Integer

[LeetCode]Reverse Integer

题目:给定一个数字,求出反转后的数字

注意的点:10100输出101,-123456=-654321,-123456789=异常溢出(程序退出)

public class Solution {
    public int reverse(int x) {
	    	long result = 0;
	        boolean isNegative = false;
	        if (x < 0) {
	        	x = -x;
	        	isNegative = true;
	        }
	        
	        while (x > 0) {
	        	result = result*10 + x%10;
	        	x /= 10;
	        }
	        if (result < 0x7fffffff) {
	        	// 2^31-1 = 0x7fffffff
	        	if (!isNegative) {
	        		return (int)result;
	        	} else {
	        		return -(int)result;
	        	}
	        } else {
	        	// overflow
	        	System.exit(1);
	        	return 0;
	        }
	    }
}