[C++]LeetCode 7:Reverse Integer(翻转整数)
来源:互联网 发布:双色球扫描查询软件 编辑:程序博客网 时间:2024/06/05 20:52
Problem:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
分析:
看似简单的逆序问题,最需要注意的是溢出。
解法一:转换为数组二分交换
解法二:直接使用x/10 ,x%10。(代码中方法)
下面主要关注的是溢出问题:
首先需要了解的是最大整数和负数,在limits.h中有宏定义,如下:
#define INT_MAX 2147483647#define INT_MIN (-INT_MAX - 1)对于本题的乘法判断溢出的方法为:
//a*b是否溢出a&&b != 0 && (INT_MAX / abs(a) < b对于加法是否溢出:
//a+b是否溢出,注意a、b为非负整数(unsigned int)a + (unsigned int)b > INT_MAX)
AC Code (C++):
class Solution {public: //1032 / 1032 test cases passed. //Runtime: 15 ms #define INT_MAX 2147483647 #define INT_MIN (-INT_MAX - 1) int reverse(int x) { int flag = 1;//设置正负指示 if (x < 0){ flag = -1; x = -x; } int num = 0; while (x > 0){ if ((num != 0 && (INT_MAX / abs(num) < 10)) || ((unsigned int)abs(num * 10) + (unsigned int)(x % 10) > INT_MAX)){//溢出 return 0; } num = num * 10 + flag * (x % 10); x = x / 10; } return num; }};
测试用例:
被下组数据WA了好久,编代码的时候可以测试下:
1028 / 1032 test cases passed.
Input:1534236469Output:1056389759Expected:0
- [C++]LeetCode 7:Reverse Integer(翻转整数)
- LeetCode 7 Reverse Integer(翻转整数)
- LeetCode | Reverse Integer(翻转整数)
- [C++]Reverse Integer整数翻转
- leetcode 7. Reverse Integer(C语言,翻转一个整数,判断是否溢出)19
- LeetCode #7 Reverse Integer 翻转整数 解题小节
- leetcode题集——reverse-integer(翻转十进制整数)
- 翻转int型整数(Reverse Integer<from LeetCode>)
- LeetCode | 7.Reverse integer(整数翻转)
- Reverse Integer 翻转整数
- 【007-Reverse Integer(翻转整数)】
- [LeetCode-7] Reverse Integer(反转整数)
- [leetcode 7] Reverse Integer(整数反转) c函数实现
- 每日一练之Reverse Integer[LeetCode No.7]-翻转整数
- 【LeetCode-面试算法经典-Java实现】【007-Reverse Integer(翻转整数)】
- Reverse Integer 翻转数字@LeetCode
- [LeetCode 7]Reverse Integer(处理整数溢出)
- LeetCode 7 :Reverse Integer ---- 反转int整数
- centOS redis安装
- App开发日报 2015-05-01 HealthKit开发之HealthKit数据操作
- 并行计算知识
- 动态数组类/对象的浅复制/对象深复制
- Java单元测试进阶之单元测试利器JUnit(新手上路)
- [C++]LeetCode 7:Reverse Integer(翻转整数)
- 题目1135:字符串排序 Java/c++
- c++_vector
- 第四章作业4
- 基于MFC的电子名片管理系统
- Java单元测试进阶之单元测试利器JUnit(测试自动化)
- Cocos2d-2.x_使用系统时间来获取随机数
- 一道“求阴影面积”初等几何题的“凑面积、做加减”解法
- 《android编程实践》阅读笔记(一)