LeetCode 007. Reverse Integer
来源:互联网 发布:先锋乒羽淘宝商城微店 编辑:程序博客网 时间:2024/06/14 05:23
Reverse Integer
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?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
这道题是要求进行数字翻转,一开始想到的是栈,代码略长,如下:
#define Maxnum 20typedef struct { int data[Maxnum]; int top;}intstack;void stackInit(intstack * sq){ sq->top = -1;}bool stackEmpty(intstack * sq){ if(sq->top == -1) return true; else return false;}int push(intstack * sq, int a){ if(sq->top == Maxnum-1) { return -1; } sq->top ++; sq->data[sq->top] = a; return 1;}int pop(intstack * sq, int &a){ if(sq->top == -1) return -1; a = sq->data[sq->top]; sq->top -- ; return 1;}class Solution {public: int reverse(int x) { intstack * sq = new intstack; stackInit(sq); //因为最小负数为-2147483648,最大正数为2147483647 //因此x=0-x这种将负数转成正数的方法是不可取的! bool negative = false; if (x < 0) negative = true; int y = 0; //54321入栈,入栈顺序为1 -> 2 -> 3 -> 4 -> 5 //-54321入栈,入栈顺序为-1 -> -2 -> -3 -> -4 -> -5 while(x) { y = x%10; push(sq,y); x = x/10; } x = 0; y = 0; int multi = 1; bool iszero = true; //将数据出栈 while(!stackEmpty(sq)) { pop(sq, y); if(!iszero || y) { x = x + y*multi; multi *= 10; iszero = false; } } return x; }};
后来在做palindrome Number时,又想到了另外一种方法:
class Solution {public: int reverse(int x) { int temp = x; int result = 0; while(temp) { result = result*10 + temp%10; temp /= 10; } return result; }};
0 0
- LeetCode 007. Reverse Integer
- 【LeetCode】007.Reverse Integer
- leetcode--007. Reverse Integer
- 【LeetCode】 007. Reverse Integer
- 【LeetCode】007.Reverse Integer
- [LeetCode 解题报告]007.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 104: Reverse Integer
- Leetcode : Reverse Integer
- 【leetcode】Reverse Integer
- [LeetCode]Reverse Integer
- LeetCode-Reverse Integer
- 熵、信息增益
- 数据结构_递归算法的应用_打印n个数的全排列数
- Lucene从入门到熟悉(一)概念&建立索引
- (黎活明老师讲学)Android学习(二)---从网络上获取网页
- Windows 内存管理的一些点点滴滴
- LeetCode 007. Reverse Integer
- hdu1028(母函数)
- UI控件使用案例<四>
- android使用lrucache与softReference对图片进行优化
- LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- HEVC ME之 整像素TZ搜索代码分析
- Intent传递对象parcelable、serializable
- 网络请求中文编码格式问题处理
- 1626. Function Run Fun