Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [?231, 231 ? 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
代碼:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cmath>
#include<string>
#include<string.h>
#include<set>
#include<map>
#include<queue>
#include<stack>
using namespace std;
int main()
{
int x;
cin>>x;
//使用類似pop和push操作
int temp;
int pop;
int rev = 0;
while(x)
{
pop = x%10;
x /= 10;
if(rev > INT_MAX/10 || (rev == INT_MAX/10 && pop>7))
{
cout<<0;
return 0;
}
else if(rev < INT_MIN/10 || (rev == INT_MIN/10 &&pop<-8))
{
cout<<0;
return 0;
}
rev = rev*10 + pop;
}
cout<<rev;
return 0;
}
本題總結(jié):
1.c++使用INT_MAX取最大INT值,為-232~232-1调衰,即-2147483648~2147483647
2.數(shù)字回文操作苟径,可以使用類似pop谷朝、push操作
pop = x %10;
rev = rev10 + pop;
x /= 10;
注意這里的rev = rev10 + pop可能會超出整數(shù)范圍蹋半,此時(shí)應(yīng)當(dāng)提前判斷是否越界鬓照!