LeetCode练习-翻转数字(Reverse Integer)

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

代码:

public class Test7 {
	
	public int reverse(int x) {
		int rev = 0;
		while (x != 0) {
			if (rev != 0 && Integer.MAX_VALUE / rev < 10&& Integer.MAX_VALUE / rev > -10)
				return 0;
			rev = rev * 10 + x % 10;
			x = x / 10;
		}

		return rev;
	}

	public static void main(String[] args) {
		System.out.println(new Test7().reverse(-2147483412));
	}
}

你可能感兴趣的:(编程练习)