大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题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
大家明天见
设置视口 要创建响应式网站,请在"meta" 您的所有网页上添加以下标记 响应式...
趋近尾声了,今天开始来讲对外的部分啦,其主角就是企业的供应链(供应商/合作商/3th Party)...
之前安装了iRedMail,使用了一段时间感觉不太理想,可能对于我这种菜鸟来说不太友好吧,现在安装Z...
在组织经营过程,除了组织能将本身资源/资产运用得当,持续产出商品/提供服务以创造价值(营收),在经营...
Virtual Judge ZeroJudge 题意 \TeX/ \LaTeX/ 输入一字串,重新...