7 Reverse Integer(数字反转Easy)

题目意思:int数字反转

考虑:越界问题

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         long ans=0;
 5         while(x){
 6             ans=ans*10+x%10;
 7             x=x/10;
 8         }
 9         return (ans > INT_MAX || ans < INT_MIN)? 0 : ans;
10     }
11 };

ps:leetcode中long比int要长,可是visual c++中long和int取值范围一样

因而有了下面这种我认为更好的代码

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         int ans=0;
 5         while(x>=10||x<=-10){
 6             ans=ans*10+x%10;
 7             x=x/10;
 8         }
 9         if(ans>INT_MAX/10||(ans==INT_MAX/10&&x>INT_MAX%10))
10             return 0;
11         if(ans<INT_MIN/10||(ans==INT_MIN/10&&x<INT_MIN%10))
12             return 0;
13         return ans*10+x%10;
14     }
15 };

 

   

posted @ 2015-06-20 09:21  影翕  阅读(224)  评论(0编辑  收藏  举报