【问题描述】
给出一个32位的有符号整数n,请将该数进行反转(正负符号不变,其余数字反转)。
反转后的数如果溢出,则输出0。
【输入形式】
输入为一行一个整数
【输出形式】
输出为一行一个整数
【样例输入1】
123
【样例输出1】
321
【样例输入2】
-123
【样例输出2】
-321
【样例说明】
32位有符号整形的取值范围为-2147483648~2147483647
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main(){
int n;
cin>>n;
string s;
if (n<0){
cout<<"-";
n = -n;
s = to_string(n);
reverse(s.begin(),s.end());
if (s[0]=='0'){
for(int i=1;i<s.size();i++){
cout<<s[i];
}
}
}
else{
s = to_string(n);
reverse(s.begin(),s.end());
if (s[0]=='0'){
for(int i=1;i<s.size();i++){
cout<<s[i];
}
}
}
return 0;
}
学到后面写出来的,不知道能不能通过测试用例
#include <iostream>
using namespace std;
int main(){
long long int n,b=0;
cin>>n;
if(n<0){
n = -n;
while(n>0){
b = b*10+n%10;
n/=10;
}
if(b>=-2147483648&&b<=2147483647){
cout<<"-"<<b;
}
else cout<<"0";
}
else{
while(n>0){
b = b*10+n%10;
n/=10;
}
if(b>=-2147483648&&b<=2147483647){
cout<<b;
}
else cout<<"0";
}
return 0;
}
正常写法