首页 > 代码库 > [LeetCode] Reverse Integer
[LeetCode] Reverse Integer
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 happens22 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。