Created
February 11, 2020 09:26
-
-
Save yitonghe00/c96518755394c5b8af59093204666200 to your computer and use it in GitHub Desktop.
7. Reverse Integer (https://leetcode.com/problems/reverse-integer/): Given a 32-bit signed integer, reverse digits of an integer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Math solution: Pull the digits and take care of the overflow | |
// Time: O(logx), 1ms | |
// Space: O(1), 36.6mb | |
class Solution { | |
public int reverse(int x) { | |
int ans = 0; | |
while(x != 0) { | |
int tail = x % 10; | |
int newAns = ans * 10 + tail; | |
// !!: Take care the overflow by checking if result is as we expected when adding newAns | |
if((newAns - tail) / 10 != ans) return 0; | |
ans = newAns; | |
x /= 10; | |
} | |
return ans; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment