【Leetcode】7.Reverse Integer 解题
来源:互联网 发布:大数据与股票预测 编辑:程序博客网 时间:2024/06/05 04:26
【题目描述】:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
【思路分析】:
先获取绝对值以及设置负号标志位。
再对结果和数据进行每一位的处理,处理一次就判断一次溢出情况。
【我的代码】:
class Solution {public: int reverse(int x) { int result = 0; int flag = x >= 0 ? 0 : 1;//为1,则在返回时加负号 int abValue = x > 0 ? x : -x; while (abValue / 10 != 0 || (abValue / 10 == 0 && abValue % 10 != 0)) { //检测溢出,不能写成result * 10 + abValue % 10 > INT_MAX,否则溢出已被截断 if (result > (INT_MAX-abValue % 10) / 10) { return 0; } result = result * 10 + abValue % 10; abValue /= 10; } return flag == 1 ? -result : result; }};
0 0
- 【Leetcode】7.Reverse Integer 解题
- [leetcode] 7. Reverse Integer 解题报告
- [Leetcode] 7. Reverse Integer 解题报告
- leetcode解题报告7. Reverse Integer
- [leetcode]7. Reverse Integer@Java解题报告
- 【LeetCode】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 7. Reverse Integer (数字反转) 解题思路与方法
- Leetcode解题笔记 7.Reverse Integer [Easy]
- LeetCode 7 Reverse Integer 解题报告
- [LeetCode 解题报告]007.Reverse Integer
- [LeetCode]7.Reverse Integer
- 114. Flatten Binary Tree to Linked List
- windows界面编程之自绘窗体(模仿腾讯qq)
- 创建动态数据窗口的两种方法
- 设计模式六大原则详解
- windows编程之音频设备的捕获
- 【Leetcode】7.Reverse Integer 解题
- 清除NT Kernel占用80端口
- C/C++系列之如何实现一个avi格式的播放器
- bdwk标题
- 打开了曾经作为程序员的编程博客,心中多少有些怀念程序中的
- win32程序中调用控制台程序
- 批量检查代理ip是否可用 curl-multi php检测ip代理是否有效
- 【Leetcode】8.String to Integer (atoi) 解题
- MySQL没有 data 目录的解决方法或者重建 data 目录