您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: