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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
难度:easy
题目:
给定32位带符号整数,反转该整数。
注意:
假定处理的环境只能存储32位带符号整数范轩为[负的2的32次方, 2的32次方-1]。 这个问题的目的在于溢出的整数返回0.
思路:两次反转,如果不变则没有溢出,如果不同分为两种情况一种是变之前尾数有0的,另一种则是溢出的。
Runtime: 16 ms, faster than 97.34% of Java online submissions for Reverse Integer.
public class Solution {
public int reverse(int x) {
int result = justReverse(x);
int reverseResult = justReverse(result);
// 120 -> 21 -> 12, so x % reverseResult == 0 is also not overflow
return reverseResult == x || x % reverseResult == 0 ? result : 0;
}
private int justReverse(int x) {
int result = 0;
while(x != 0) {
int m = x % 10;
x = x / 10;
result = result * 10 + m;
}
return result;
}
}