您的位置:首页 > 其它

反转整数

2017-09-08 10:05 253 查看
/*

问题描述:将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回0

来源:LintCode

作者:syt
日期:2017-9-8

思路:测试数据中存在越界数,所以转化为字符串处理即可

*/

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

/*
* @param n: the integer to be reversed
* @return: the reversed integer
*/
int reverseInteger(int n) {
// write your code here
int result = 0;

string nums = to_string(n);
string max = to_string(INT_MAX);

int i = 0;
int j = nums.length() - 1;
while (i < j)
{
char tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
i++;
j--;
}
cout << nums << endl;
cout << max << endl;
if (nums.length() == max.length() && nums > max)
result = 0;
else
result = atoi(nums.c_str());
if (n < 0)
result = -result;
return result;

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