Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Example 2:
Example 3:
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.
关键点:
1.题目给出输入的数小于INT_MAX,但反转过后不一定小于INT_MAX,所以要进行判断。
#include<iostream>
#include<climits>
using namespace std;
intinverse(intx){
intc,y,newnum=0,oldnum=x;
c=oldnum/10;
y=oldnum%10;
while(oldnum!=0)
{
if(newnum>INT_MAX/10|| newnum
{
return0;
}
newnum=newnum*10+y;
oldnum=c;
c=oldnum/10;
y=oldnum%10;
}
returnnewnum;
}
intmain(intargc,constchar* argv[]) {
// insert code here...
inta,b;
while(cin>>a){
b=inverse(a);
cout<
}
cout << "Hello, World!\n";
return 0;
}
网友评论