首页 > 其他 > 详细

【Leetcode】 #7 Reverse Integer

时间:2015-06-01 22:10:25      阅读:303      评论:0      收藏:0      [点我收藏+]

Reverse digits of an integer.

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

 

测试用例:

  • 123………………321
  • -123………………-321
  • 1200………………21
  • 45134543545…………0(overflow)
  • 2147483646………………0(虽然它小于最大值2147483647,但是调转过来之后溢出!)


最后两个陷阱是不容易发现的。

int类型的最大值是2147483647。

下面是代码:

 1 public static int reverse(int x) {
 2         boolean isNegative=false;
 3         if(x<0){
 4             isNegative=true;
 5             x*=-1;
 6         }
 7         if(x>0x7FFFFFFF)
 8             return 0;
 9         int result=0;
10         boolean bigin=false;
11         int y=0;
12         while(x>0){
13             y=x%10;
14             x/=10;
15             if(y!=0){
16                 bigin=true;
17             }
18             if(bigin){
19                 if(result>214748364||(result==214748364&&y>7))   //防止调转过来溢出
20                     return 0;
21                 result*=10;
22                 result+=y;
23             }
24         }
25         if(isNegative)
26             result*=-1;
27         return result;
28     }

 

【Leetcode】 #7 Reverse Integer

原文:http://www.cnblogs.com/darkhorse-pxf/p/4544935.html

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