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.
import(
"fmt"
)
func reverse(x int) int {
var IsNeg bool = false
var Resp int = 0
var Power int = int(math.Pow(2, 31))
if x < 0 {
IsNeg = true
x = -1 * x;
}
for x > 0 {
var Curr int = x%10
Resp = Resp * 10 + Curr
x = x/10;
}
if IsNeg {
Resp = -1 * Resp
}
if Resp > Power-1 || Resp < -1 * Power {
return 0
}
return Resp
}
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
isNeg = False
resp = 0
power = 2**31
if x < 0:
isNeg = True
x = -1*x
while x > 0:
mod = x%10
resp = resp*10 + mod
x = int(x/10)
if isNeg:
resp = -1*resp
if resp > power-1 or resp < -1*power:
return 0
return resp