2.leetcode-Reverse Integer
来源:互联网 发布:源码说明文档模板下载 编辑:程序博客网 时间:2024/05/20 16:35
1.题目描述
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
2.基本想法
这道题就是翻转数字,本身看着没有难度。难点在于:此种题目一般要考虑的情况都非常多。
- 求出int类型最大正数与最大负数?
- 如果输入用例是最大整数与最大负数,它们的处理情况是否一样?
- 如何判断溢出?
- 要考虑正负号?
测试用例:
- 32位int类型最大值
- 32int类型最小值
- -123
- 123
- -1463847412
3.代码如下
c++
int reverse(int x) { if(x==0) return 0; bool sign=false; int MaxLimit=((unsigned int)0-1)>>1;/* 出错地方:写成了 int MaxLimit=((signed int)0-1)>>1 导致输入任何数输出都为0 */ int MinLimit=MaxLimit+1; if(x==MinLimit) return 0; if(x<0) { sign=true; x=-x; } int res=0; int a; while(0<x) { a=x%10; x=x/10; if(res<MaxLimit/10 || (MaxLimit/10==res && a<=MaxLimit%10) )/* 出错地方:写成了(MaxLimit/10==res && a==MaxLimit%10),这样输入MaxLimit-1,则会输出0*/ { res=res*10+a; }else { res=0; break; } } if(sign) res=-1*res; return res;}
python
class Solution(object): def reverse(self,x): """ :type x: int :rtype: int """ MaxLimit=0x7FFFFFFF x= 0 if -1*(MaxLimit+1)==x else x sign= True if x<0 else False x= -x if sign else x res=0 while(x!=0): digit=x%10 x=x//10 if (res<MaxLimit//10 or (res==MaxLimit//10 and digit<=MaxLimit%10) ): res = res*10 + digit else: res=0 break if(sign): res=-1*res return res
原谅我丑陋的python代码
0 0
- 2.leetcode-Reverse Integer
- 2.leetcode题7:Reverse Integer
- LeetCode:Reverse Integer
- LeetCode: Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode : Reverse Integer
- [LeetCode] Reverse Integer
- Leetcode: Reverse Integer
- LeetCode 7 - Reverse Integer
- leetcode 104: Reverse Integer
- Leetcode : Reverse Integer
- 【leetcode】Reverse Integer
- [LeetCode]Reverse Integer
- LeetCode-Reverse Integer
- [leetcode] Reverse Integer
- LeetCode - Reverse Integer
- leetcode之Reverse Integer
- LeetCode | Reverse Integer
- Spring Boot-创建Spring Boot项目
- Maven的POM.xml详解(二)
- Github-OSGeo
- VxWorks内存分配分析
- 实现一个函数,可以左旋字符串中的k个字符。 AABCD左旋一个字符得到ABCDA AABCD左旋两个字符得到BCDAA
- 2.leetcode-Reverse Integer
- Android之ndk-build出现c:28:51: error: 'get_string' undeclared here (not in a function)解决办法
- eclipse删除workspace空间&workspace配置
- (六)任务分解法(WBS)
- python 有序字典
- 8个常用字符串处理函数
- MySQL 对于千万级的大表要怎么优化?
- Maven的POM详解(三)
- CSDN日报20170507 ——《技能终将过时,而能力与时俱进》