当前位置: 代码迷 >> 综合 >> LeeCode-整数翻转
  详细解决方案

LeeCode-整数翻转

热度:96   发布时间:2023-11-11 09:49:13.0

目录

  • 一、题目链接
  • 二、题目介绍
  • 三、程序
  • 四、重点内容
    • 4.1 join()用法
    • 4.2 列表的基础用法
      • 4.2.1 翻转

一、题目链接

https://leetcode-cn.com/problems/reverse-integer.

二、题目介绍

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [?231, 231 ? 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123
输出:321
示例 2:

输入:x = -123
输出:-321
示例 3:

输入:x = 120
输出:21
示例 4:

输入:x = 0
输出:0

提示:

-231 <= x <= 231 - 1

三、程序

class Solution:def reverse(self, x):list_x = list(str(x)) #整数先变成字符串,再变成列表if x < 0:list_x.remove("-")list_x.reverse()   #list_x[::-1]out = "".join(list_x)out =  -int(out)  #别忘了字符串变成整形else:list_x = list_x[::-1]out = "".join(list_x)out =  int(out)if  not     -pow(2,31)<= out <= pow(2,31)-1:# -2**31<= out <= 2**31-1out = 0return out#考察知识点:
#(1)列表的相关操作:移除(remove); 翻转(reverse(),list[::-1],reversed());
# (2) 字符串、整型、字符串合并(join用法)
# (3)大小判断 次方写法 pow(x,y) = x^y输入
123
输出
321
预期结果
321

四、重点内容

4.1 join()用法

(1) 字符串拼接
eg:

str = "-"
list = ["a","b","c","d"]
out = str.join(list)
print(out)  #a-b-c-dG:\PACHONG\venv\Scripts\python.exe G:/PACHONG/7_28/demo1.py
a-b-c-dProcess finished with exit code 0

(2) os 模块 地址的拼接
os.path.join()

import osPath1 = 'a'
Path2 = 'b'
Path3 = 'c'Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
print ('Path10 = ',Path10)
print ('Path20 = ',Path20)输出Path10 = abc
Path20 = a\b\c

4.2 列表的基础用法

4.2.1 翻转

(1) list.reverse()
(2) list.[::-1]