LintCode 413. 反转整数
- LintCode
- 将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。
样例
- 给定
x = 123
,返回321
。 - 给定
x = -123
,返回-321
。
Java 代码
public class Solution { /** * @param n: the integer to be reversed * @return: the reversed integer */ public int reverseInteger(int n) { // write your code here boolean negative = n < 0; if (negative) n = -n; long r = 0; while (n > 0) { r = r * 10 + n % 10; n = n / 10; } if (negative) r = -r; if (r > Integer.MAX_VALUE || r < Integer.MIN_VALUE) return 0; return (int)r; }}