整数反转
- Time Limit: 2000/1000ms (Java/Others)
- Problem Description:
- 给定一个 32 位 int 型的整数, 把这个整数反着输出, 如 123, 输出 321. 反转过程中有可能会有溢出 32 位 int 的情况, 则输出 0.
- Input:
- 输入包含多组测试数据, 对于每组数据, 输入一个 int 型整数.
- Output:
- 对于每组数据, 输出反转之后的答案.
- Sample Input:
- 123 1230 -123
- Sample Output:
- 321
- 321
- -321
- 解题思路: 将数据类型定义为 64 位 long long 类型, 只要反转之后的值大于 32 位 int 最大值或者小于 32 位 int 最小值, 则输出 0, 否则输出反转之后的值, 水过!
- AC 代码:
- #include<bits/stdc++.h>
- using namespace std;
- typedef long long LL;
- const LL maxn=(1LL<<31)-1;// 获取 int 最大值和最小值
- const LL minn=1<<31;LL n,m;
- int main(){
- while(cin>>n){m=0;
- while(n){m=m*10+n%10;n/=10;}
- if(m>maxn||m<minn)cout<<0<<endl;// 大于 int 最大值或者小于 int 的最小值, 则输出 0
- else cout<<m<<endl;// 否则输出反转之后的数字
- }
- return 0;
- }
来源: http://www.bubuko.com/infodetail-2657533.html