码迷,mamicode.com
首页 > 其他好文 > 详细

7.Reverse Integer(long long类型)

时间:2015-02-10 09:17:49      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to showspoilers.

Have you thoughtabout this?

Here are some good questions to ask before coding. Bonus points for you ifyou have already thought through this!

If the integer‘s last digit is 0, what should the output be? ie, casessuch as 10, 100.

Did you notice that the reversed integer might overflow? Assume the inputis a 32-bit integer, then the reverse of 1000000003 overflows. How should youhandle such cases?

For the purpose of this problem, assume that your function returns 0 whenthe reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

HideTags

 Math


#pragma once
#include<iostream>
#include<queue>
using namespace std;


//long 固定为32位 int 在32位机器上是32位,long long 固定是64位
int reverse(int x) {
	long long val = abs(x);//绝对值
	long long result = 0;
	long long up = 2147483647;
	long long down = 2147483648;
	down = -down;//2147483648计算机认为是unsigned int 不能加负号,曲线救国
	int flag = 1;//符号
	if (x < 0)
		flag = -1;
	queue<int> q;
	int temp = 0;
	while (val > 0)
	{
		temp = val % 10;//取余
		q.push(temp);
		val /=10;
	}
	while (!q.empty())
	{
		result =result*10 + q.front();
		q.pop();
	}
	if (result > up || result < down)
		return 0;
	return flag*result;
}
void main()
{
	cout << reverse(1000000003) << endl;
	cout << reverse(12345) << endl;
	system("pause");
}


 

7.Reverse Integer(long long类型)

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43691709

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!