7. Reverse Integer
Description
Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Constraints
Approach
Links
YouTube
Examples
Input: 123
Output: 321
Solutions
/**
* Time complexity : O(log(x)). There are roughly log10(x) digits in x.
* Space complexity : O(1)
*/
class Solution {
public int reverse(int x) {
int n = 0, flag = (x < 0)? -1: 1;
x *= flag;
while(x > 0) {
int pop = x%10;
if(n > Integer.MAX_VALUE/10 ||
(n == Integer.MAX_VALUE/10 && pop > 2)) return 0;
n = (n*10) + pop;
x /= 10;
}
return n * flag;
}
}
Follow up
Last updated
Was this helpful?