LeetCode7 Reverse Integer 题解(数的逆序)
2018-03-19 14:49
337 查看
LeetCode7 Reverse Integer 题解
题目Given a 32-bit signed integer, reverse digits of an integer.
输入输出实例
input:123
output:321
intput:120
output:21
input:-123
output:-321
核心算法
int result = 0; while(n!=0){ result = result*10+n%10; n /= 10; }
其他注意的地方
考虑特殊情况,有时需要特判
如 input:0
input:-2147483648(即INT_MIN)
数据溢出:
如:long long a = 1<<31-1;
等号右边溢出 1默认为int型,1<<31溢出
修改:long long a = 1ll<<31-1
或者 long long a = INT_MAX;
代码
class Solution { public: int reverse(int x) { string s; if(x>=0){ long long result = 0; while(x!=0){ result = result*10+x%10; x/=10; } if(result<=INT_MAX) return result; else return 0; }else{ long long a = x; a = -1ll*a; //注意,若直接使用x=-1*x的话,当遇到输入x为INT_MIN时,会出现数据溢出 long long result = 0; while(a!=0){ result = result*10+a%10; a/=10; } if(result<=1ll<<31) //注意:若使用1<<31,会出现数据溢出(1默认为int型) int的数据范围为[-1<<31 - 1<<31-1] return (-1*result); else return 0; } } };
相关文章推荐
- LeetCode题解:Reverse Integer (3种解法)
- leetcode题解||Reverse Integer 问题
- leetcode题解||Reverse Integer 问题
- [Week 1]【Leetcode】Reverse Integer(逆序问题)
- leetcode-7 Reverse Integer 十进制数字逆序输出
- LeetCode: Reverse Integer 解题报告
- leetcode Reverse Integer(python)
- LeetCode:Reverse Integer
- leetcode_reverse_integer
- LeetCode 7 :Reverse Integer ---- 反转int整数
- [LeetCode] Number of 1 Bits & Reverse Integer - 整数问题系列
- LeetCode题解——8 String to Integer (atoi)
- leetcode: Reverse Integer
- leetcode Reverse Integer
- leetcode — reverse-integer
- [LeetCode] 087: Reverse Integer
- LeetCode: Reverse Integer
- LeetCodet题解--12. Integer to Roman
- leetCode --Reverse Integer以及java基本类型
- LeetCode Reverse Integer 反转整数