大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
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 [-2^31, 2^31 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Input: x = 123
Output: 321
Input: x = -123
Output: -321
Input: x = 120
Output: 21
Input: x = 0
Output: 0
-2^31 <= x <= 2^31 - 1
首先先簡單的翻譯一下題目
給一個32-bit的有號整數x
,把這個x
顛倒過來,並回傳顛倒過後的x
。如果顛倒過後的x
的值的範圍不在-2^31 <= x <= 2^31 - 1
,則回傳0。
想法是這樣,先不管他正負號,先把他轉成str的型態,就可以得到每一個位數的數字。接著,因為要顛倒過來,所以位數是會愈來愈大,從10^1, 10^2, 10^3, ...10^n。
作法大致上是這樣
class Solution:
def reverse(self, x: int) -> int:
rev = 0
multiple = 0
if x < 0:
str_x = str(-x)
else:
str_x = str(x)
for index in range(len(str_x)):
rev += int(str_x[index])*(10**multiple)
multiple += 1
if x < 0:
rev = -rev
if (-2**31) > rev or rev > (2**31-1):
rev = 0
return rev
class Solution:
def reverse(self, x: int) -> int:
rev = 0
if x < 0:
list_x = list(str(-x))
else:
list_x = list(str(x))
print(list_x)
for index in range(len(list_x)):
list_x[index], list_x[len(list_x)-index-1] = list_x[len(list_x)-index-1], list_x[index]
if (index-(len(list_x)-index-1)) == 0 or ((index+1) == (len(list_x)-index-1) and index == (len(list_x)-index-1)-1):
break
rev_str = str(list_x).replace(" ", "").replace(",", "").replace("[", "").replace("]", "").replace("'", "")
if x < 0:
rev = -int(rev_str)
else:
rev = int(rev_str)
if (-2**31) > rev or rev > (2**31-1):
rev = 0
int reverse(int x){
long int rev = 0;
while(x != 0){
rev *= 10;
rev += (x%10);
x = x/10;
}
// INT_MIN: -2^31 = -2147483647-1
// INT_MAX: 2^31-1 = 2147483647
return (rev < INT_MIN || rev > INT_MAX)? 0 : rev;
}
Python
C
大家明天見