Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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.
My code:
import numpy as np
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x>2**31-1 or x<-2**31:
return 0
flag=False
if x<0:
x=abs(x)
flag=True
tmp_list=[]
remain=0
while x!=0:
remain=x%10
#print('remains now %d'%remain)
tmp_list.append(remain)
x=int(np.floor(x/10))
#print(x)
new_x=0
for i in range(len(tmp_list)):
index=i
#print(tmp_list[index])
new_x=new_x*10+tmp_list[index]
if new_x>2**31-1 or new_x<-2**31:
return 0
if flag:
return -new_x
return new_x
Solution:
https://leetcode.com/problems/reverse-integer/description/