LeetCode 第7题 Reverse Integer (easy)——python
来源:互联网 发布:苏州市人工智能学会 编辑:程序博客网 时间:2024/06/07 10:31
题目来源:
https://leetcode.com/problems/reverse-integer/description/
题目分析:
本文是给定一个32位的有符号数,让我们将其逆序输出。它给定了这样的几个例子:
由它给的例子,我们可以注意到在实现程序时要注意符号位是正常输出的,此外倒序过来有可能会0来打头,这个也是不允许的。看到这个题目,我一开始想用reverse()来做,然后一直在考虑怎样可以省略前面的0,直到参考了其它人的程序才直到本人果然是菜鸟!在实现程序时,知道一下几点程序就可以顺利的写出了!
1.reverse函数的使用范围
reverse()函数是用于反向列表中的元素,对于其它的对象是不适用的,因此本题最好的方法不是采用reverse()。关于逆序,我们还可以想到切片的方法,可以进行切片的对象是字符串,列表,元组,同样不包含整数,所以本题我们要注意将整数型数据转化成字符串类型的数据(str(),int())
2.关于逆序后多余0的情况
由于最后我们在进行逆序操作后,返回值为整型,因此会有将字符型转化为整形的操作,经过编译,可以发现int()函数自动将前面多余的0给删去了,因此不需要考虑如何去除前面的0。
3.关于32位有符号数的取值范围
我在写程序的时候,将其范围写成了-2**31~2**32,结果始终通不过编译,经查询才知道其范围应该是-2**32/2~(2**32)/2-1,这是需要万分注意的。
实验代码:
注意了以上几点后,所写的代码如下:
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if(x<0): y=-1*int((str(-x))[::-1]) else: y=int((str(x))[::-1]) if (y>(2**32/2-1) or y<(-(2**32/2))): y=0 return (y)
阅读全文
0 0
- LeetCode 第7题 Reverse Integer (easy)——python
- 【LeetCode】LeetCode——第7题:Reverse Integer
- leetcode第七题(easy)——Reverse Integer
- [Leetcode 7, Easy] Reverse integer
- 【LeetCode】(7)Reverse Integer(Easy)
- LeetCode #7 - Reverse Integer - Easy
- leetcode第7题——*Reverse Integer
- 【Leetcode】Reverse Integer(easy)
- Easy 7题 Reverse Integer
- LeetCode刷题(C++)——Reverse Integer(Easy)
- LeetCode OJ 7 Reverse Integer [easy]
- LeetCode 第 7 题(Reverse Integer)
- leetcode第7题,Reverse Integer
- leetcode 第7题 Reverse Integer
- 【leetcode】7—reverse integer
- python学习——leetcode第七题Reverse Integer
- LeetCode 7 — Reverse Integer(C++ Java Python)
- 【LeetCode 7】Reverse Integer(Python)
- 杂货边角(2):AT&T和INTEL汇编语法
- 使用百度BAE和新浪SAE部署web项目
- C#学习笔记之——学生信息输入系统(Dictionary)
- 69 个经典 Spring 面试题和答案
- C++——OOP(Object-Oriented Programming) vs. GP(Generic Programming)
- LeetCode 第7题 Reverse Integer (easy)——python
- 网站部署到Linux服务器上并添加https证书
- 科研生活
- malloc、calloc、realloc的区别
- jquery validate
- 转-关于书上说的“编译的时候分配内存”
- Netflix是如何利用内部Spot市场来节约成本的
- ABP 分析之路的开始
- Ext4 在tips中展示Grid中的某一列的所有值