9/4 每日一題(反轉整數)
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Constraints:
-231 <= x <= 231 - 1
class Solution:
def reverse(self, x: int) -> int:
if x==0:
return 0
str_x=str(x)
if str_x[-1]=='0':
str_x=str_x[:-1]
print(f'str_x={str_x}')
if '-' in str_x:
rev = str_x[-1:0:-1]
print(f'rev={rev}')
x=int(rev)*-1
if -2**31 <=x < 2**31 :
return x
else:
return 0
rev=str_x[::-1]
print(f'rev={rev}')
x=int(rev)
if -2**31 <= x < 2**31:
return x
else:
return 0
------------------------------
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
isNegative = x < 0
if isNegative:
x *= -1
digits = []
length = 0
while (x != 0):
digits.append(x % 10)
x = x // 10
length += 1
res = 0
for i in range(length):
res += 10**(length - i - 1) * digits[i]
if isNegative:
res *= (-1)
if res < (-2)**31:
return 0
else:
return res
if res > (2)**31 + 1:
return 0
else:
return res標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁