leetcode小白解题记录——第七题
来源:互联网 发布:医疗答题软件 编辑:程序博客网 时间:2024/05/12 06:29
7. Reverse Integer
- Total Accepted: 165524
- Total Submissions: 696092
- Difficulty: Easy
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
这个问题也比较直观,关键是一个考虑运算的时候有可能出现溢出问题,对于溢出问题,有如下的解决方案:
1.
class Solution {public: int reverse(int x) { double s=0;//一定要设置成double,否则 下面while循环里 s = s * 10 + x % 10; s每次都乘以10,可能会导致整数溢出 int flag=1; if(x==0) return 0; if(x<0) { flag=-1; x=x*(-1); } while(x>0){ s = s * 10 + x % 10; x=x/10; } s=s*flag; return (s > INT_MAX || s < INT_MIN? 0 : s); }};2. 在做乘10运算的时候先判断一下
- public class Solution {
- public int reverse(int x) {
- if (x == 0) return 0;
- int res = 0;
- int sign = 1;
- if (x < 0) {
- sign = -1;
- x = -1 * x;
- }
- while (x != 0) {
- if (res > (Integer.MAX_VALUE - x % 10) / 10) {
- return 0;
- }
- res = res * 10 + x % 10;
- x = x / 10;
- }
- return res * sign;
- }
- }
0 0
- leetcode小白解题记录——第七题
- leetcode小白解题记录——第一题
- leetcode小白解题记录——第二题
- leetcode小白解题记录——第三题
- leetcode小白解题记录——第四题
- leetcode小白解题记录——第五题
- leetcode小白解题记录——第六题
- leetcode小白解题记录——第九题
- leetcode小白解题记录——第八题
- leetcode小白解题记录——第十题
- leetcode小白解题记录——第十一题
- leetcode第七周解题报告
- leetcode第七周解题总结
- [LeetCode] Triangle 解题记录
- LeetCode解题记录
- [LeetCode]Valid Sudoku解题记录
- LeetCode解题记录(1)
- LeetCode解题记录(2)
- c++11新特性--Lambda表达式
- NYOJ 513 A+B Problem IV
- HTML标签全称md
- python的策略模式
- 80C51的串口原理
- leetcode小白解题记录——第七题
- 有关C++面向对象面试题
- 不用输入法打字
- [完]Spark安装学习实践
- LeetCode[299] Bulls and Cows
- 数据结构实验之链表八:Farey序列
- 函数参数执行顺序
- 单片机独立按键
- cocos2d-x(7)——字体标签CCLabel(转载)