Leetcode(C++)——7. 整数反转
2019-03-05 21:40
405 查看
7. 整数反转
①题目描述
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
注意: 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
②示例
输入: 123 输出: 321
输入: -123 输出: -321
输入: 120 输出: 21
③解法
方法一:长字节转换法偷懒的方法,long int的字节长度为32位,直接将x读入长字节y就不存在溢出的问题
源程序:
class Solution { public: int reverse(int x) { int flag = x > 0 ? 1 : -1; long int y = (long int)x; y = y * flag; int tmp = 0; long int result = 0; while(y > 0) { tmp = y % 10; result = result * 10 +tmp; if(flag * result > INT_MAX || flag * result < INT_MIN) return 0; y = y / 10; } return flag * result; } };
Leetcode的测试结果:
每次取x最后一位,转移到结果rev中去,判断rev和INT_MAX/10、INT_MIN/10的大小,决定是否溢出。
class Solution { public: int reverse(int x) { int rev = 0; while (x != 0) { int pop = x % 10; x /= 10; if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0; if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; } };
Leetcode的测试结果:
和方法二类似,不过添加了字符串判断是否溢出。
class Solution { public: string int2str(int x) { string s = ""; while(x > 0) { s += '0' + x % 10; x /= 10; } //cout<<s<<endl; return s; } int str2int(string s) { int result = 0; for(int i = 0; i < s.length(); i++) { result = result * 10 + int(s[i] - '0'); } //cout<<result<<endl;; return result; } int reverse(int x) { int flag = x > 0 ? 1 : -1; if(x == -2147483648) return 0; x = x * flag; string s = int2str(x); if(s.length() <= 9) return flag * str2int(s); else { if(s[0] == '2') { int tmp = str2int(s.substr(1, s.length() - 1)); if(flag == -1 && tmp > 147483648) return 0; if(flag == 1 && tmp > 147483647) return 0; } else if(s[0] >= '3') { return 0; } return flag * str2int(s); } } };
Leetcode的测试结果:
④总结
溢出问题是个很大的问题,以后面试之类可能会经常遇到,做个笔记!
相关文章推荐
- LeetCode题解(python)-7. 整数反转
- LeetCode7.python实现:整数反转问题☆
- leetcode 7. 反转整数(c++版)
- LeetCode Reverse Integer 反转整数
- 【C/C++】实现将一个整数反转
- leetcode之7整数反转
- LeetCode 7. Reverse Integer 整数反转
- leetcode 7. 整数反转(Java版)
- LeetCode第七题--反转32位的整数
- leetcode 反转字符串 (C++实现)
- 【菜鸡的LeetCode答案】【C#】7.反转整数
- C++ - 整数反转
- leetcode 7.整数反转
- python实现leetcode-第七题-整数反转
- [leetcode] Reverse Integer 反转一个整数
- LeetCode 7 :Reverse Integer ---- 反转int整数
- leetcode-整数反转
- 【leetcode】7.整数反转
- Java&LeetCode 初入门——007. 整数反转
- LeetCode 7. Reverse Integer C++--带正负号数字反转