반응형
Problem:
Code 1 :
I used String API in Python.
First, convert Integer X to String
Second, check if last character is 0 or not reverse string
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
s = str(x)
negativeFlag = 1
if s[0] == '-':
negativeFlag = -1
s = s[1:]
index = 0
while index<len(s) and s[index] =='0':
index += 1
s = s[index:]
result = negativeFlag*int(s[::-1])
if result > (2**31-1) or (-2**31)>result :
return 0
return result
Code 2:
I'm not sure if it is right way that interviewer wants for me to do ...
So I tried to solve it in a different way
In the second code below, I used divide operation. (Integer division)
Divided X by 10
The remainder number would be new number in the result.
class Solution:
def reverse(self, x: int) -> int:
# check negative or positive
sign = 1 if x>0 else -1
x= abs(x)
# reverse
tail = 0
result = 0
while x:
x, mod = divmod(x, 10)
result = result*10 + mod
#print(f'x:{x} mod:{mod} result:{result}')
result = sign*result
if result < (-2**31) or result > (2**31-1):
return 0
else:
return result
English Vocabulary Expression
modulus operator : 나머지 구하는 것 %
% : percent sign
remainder : 나머지
11/4 = 2...3
"Eleven divided by four is two remainder three"
반응형