leetcode NO.7 整数反转 腾讯精选练习50
2019-05-11 17:31
477 查看
题目描述
第二题的NO4. 寻找两个有序数组的中位数,之前写过有兴趣的可以看这里,还是写的很认真的https://blog.csdn.net/qq_35547281/article/details/86676941
第三题的NO5.最长回文子串,在这里https://blog.csdn.net/qq_35547281/article/details/86690418
等下次没空我就交这两篇上去好了嘻嘻
言归正传,今天这题虽然比较简单但是还是复习几个简单的数据结构的概念,还是有一点收获的
首先放上我自己写的冗长的代码
class Solution: def reverse(self, x: int) -> int: if x > 0: count = 1 x = x else: count = -1 x = -x x = list(str(x)) for i in range(len(x)//2): temp = x[i] x[i] = x[len(x)-i-1] x[len(x)-i-1] = temp x = count*int(''.join(x)) if abs(x)>2**31: x = 0 return x
代码就不写详细的注释了,因为都比较简单。
讲一下思路就是,先用count定符号,int换list后颠倒顺序,再换回int,判断逆序后绝对值是否大于2312^{31}231,超过就返回0,不超过就是这个数了
主要复习到的概念是怎么将int 转换称 list,再从list 换回 int
x = list(str(x))
x = count*int(’’.join(x))
靠得就是这两句要记下来
同时复习一下这些个东西之间怎么转换
x = 123 b = str(x) print(b) for i in range(len(b)): print(b[i]) for i in b: print(i) #如果用这种循环来导出的话,直接下标就是对应字符串的元素值 y = list(str(x)) print(y) a = "" for i in y: a += i print(a) p = [int(x) for x in y] print(p) q = [] for i in y: q.append(int(i)) print(q) z = int(''.join(y)) print(z)
下面来观摩一下大神的做法,两行搞掂
class Solution: def reverse(self, x: int) -> int: r = x // max(1, abs(x)) * int(str(abs(x))[::-1]) return r if r.bit_length() < 32 or r == -2**31 else 0
直接用一手str[::−1]str[::-1]str[::−1]反转顺序,这说明了我对这些个内置的函数的技巧真的不熟悉,要多多积累了,前面判断正负号也很巧妙,就是用的数学上一个很经典的方法,还把分母为0规避了,但是我敲代码的时候就没想到,可恶啊!
相关文章推荐
- [leetcode] Reverse Integer 反转一个整数
- LeetCode第7题:整数反转 之 先从简单刚起(C++)
- LeetCode Reverse Integer 反转整数
- Leetcode腾讯精选_编号:104 --python
- 【LeetCode41-50】找出丢失最小正整数,计算蓄水量,检测?*匹配(44),跳跳棋,全排列,矩阵逆转,颠倒字母重新排序(auto,set/multiset,vector初始化),n次方
- LeetCode 7 反转整数
- Leetcode腾讯精选_编号:237 --python
- Python编程练习.整数反转
- leetcode之7整数反转
- [leetcode]反转整数
- Leetcode腾讯精选_编号:292 --python
- leetcode reverse Integer(反转整数)
- LeetCode7. 整数反转
- leetcode7. 整数反转
- [置顶] [LeetCode] Reverse Integer 整数反转
- [leetcode 7] 整数反转 python
- LeetCode 7. 整数反转
- leetcode--整数反转
- 【LeetCode】- Reverse Integer(将一个整数反转)
- Leetcode腾讯精选_编号:344 --python