首页 > 其他 > 详细

[LeetCode] Reverse Integer

时间:2014-10-03 15:46:24      阅读:293      评论:0      收藏:0      [点我收藏+]

Reverse digits of an integer.

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

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <climits>
 4 
 5 using namespace std;
 6 
 7 int Solve(){
 8     int data_in;
 9     cin>>data_in;
10 
11     bool ispositive = data_in>=0?true:false;
12     int data_ret = 0;
13 
14     while(data_in){
15         data_ret *= 10;
16         int add = data_in % 10;
17 
18         if((ispositive&&(INT_MAX -data_ret)>=add) ||
19            (!ispositive&&(INT_MIN -data_ret)<=add))
20             data_ret += add;
21         else return -1;//overflow happens
22 
23         data_in /= 10;
24     }
25 
26     return data_ret;
27 }
28 
29 int main()
30 {
31     freopen("txt.in","r",stdin);
32     freopen("txt.out","w",stdout);
33 
34     int case_num=0;
35     cin>>case_num;
36 
37     for(int i=0;i<case_num;++i){
38         cout<<"Case "<<i+1<<": "<<Solve()<<endl;
39     }
40 
41     return 0;
42 }

txt.in

9
89
89000
00789
1000000003
0
000
-789
-789000
-0

txt.out

Case 1: 98
Case 2: 98
Case 3: 987
Case 4: -1
Case 5: 0
Case 6: 0
Case 7: -987
Case 8: -987
Case 9: 0

 

[LeetCode] Reverse Integer

原文:http://www.cnblogs.com/zhouyoulie/p/4004954.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!