码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Reverse Integer

时间:2014-10-03 16:30:14      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   for   strong   sp   div   

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

标签:style   blog   color   io   os   for   strong   sp   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!