您的位置:首页 > 其它

lintcode-413-反转整数

2017-08-14 12:10 281 查看

413-反转整数


将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

样例

给定 x = 123,返回 321

给定 x = -123,返回 -321

标签

整数


思路

利用取余和除法取出整数每一位,需要注意整数越界问题

code

class Solution {
public:

/*
* @param n: the integer to be reversed
* @return: the reversed integer
*/
int reverseInteger(int n) {
// write your code here
bool isNeg = (n < 0);
n = abs(n);
long long res = 0;
do {
res *= 10;
res += n % 10;
n = n / 10;
}
while (n > 0);
if (res > INT_MAX) {
res = 0;
}
if (isNeg == true) {
return -1 * res;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: