LeetCode 7 - Reverse Integer
2015-05-12 22:05
531 查看
一、问题描述
Description:
Reverse digits of an integer.
For example:
Input x = 123, return 321
Input x = -123, return -321
二、解题报告
本题是对一个整数进行逆转(按整数位),其实思路比较直观:从个位开始,求出每一位并入栈。然后从栈中弹出每一个位,与 10n 相乘并各自相加,直到栈为空为止。class Solution { public: int reverse(int x) { uint64_t n = x>0 ? x:-x; stack<int> s; // 存储每一位 while(n) { s.push(n%10); n = n/10; } uint64_t m10 = 1; while(!s.empty()) { n += m10 * s.top(); s.pop(); m10 *= 10; } if(n > INT_MAX) // 如果超出范围 return 0; else return x>0? n:-n; } };
注意,逆转以后如果值超出了
int的上界,则返回0。
LeetCode答案源代码:https://github.com/SongLee24/LeetCode
相关文章推荐
- [LeetCode] Reverse Integer
- C实现 LeetCode->Reverse Integer
- LeetCode:Palindrome Number,Reverse Integer
- [LeetCode]题解(python):007-Reverse Integer
- LeetCode:07: Reverse Integer
- LeetCode Reverse Integer
- LeetCode------Reverse Integer
- Leetcode: Reverse Integer
- LeetCode-Reverse Integer
- 【leetcode刷题笔记】Reverse Integer
- 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-Reverse Integer
- LeetCode之7 --- Reverse Integer