leetcode_07_Reverse Integer (easy)

题目:

Reverse Integer

Total Accepted: 102355 Total Submissions: 436373 Difficulty: Easy

Reverse digits of an integer.

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

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

 解题:
1、翻转时从右到左第一个不为零的数开始计算
2、与最大数比较是否溢出
最开始敲的代码:
#include <iostream>
using namespace std;
class Solution {
public:
    int reverse(int x) {
     if(abs(x)<=0)//越界后,abs(x)为负数
              return 0;
        int y = 0;
        int max = 1;
        int i,j;
        while(abs(x)/10/max>=1){// abs()求得是正数的绝对值。fabs()求得是浮点数的绝对值
            max*=10;
        }
        for(i=max,j=1;i>=10;i/=10,j*=10){
//            y+= (int)(x/i)*j;//转换为整形
//            x-= (int)(x/i)*i;
            y+= (x/i)*j;
            x-= (x/i)*i;

        }
       if(max<1000000000){
            y+= (int)(x/i)*j;
            return y;
        }
        if(( y<=147483647&&(int)(x/i)==2  )||(int)(x/i)<2){
            y+= (int)(x/i)*j;
            return y;
        }
        return 0;
    }
};
int main(int argc, const char * argv[]) {
 
    Solution a;
    int j = a.reverse(-2147447412);
    //1231231231
    cout<<j<<endl;
    //有符号整形最大值2147483647
//    int i = 2147483647;
//    cout<<i<<endl;
    return 0;
}

 
 //有符号整形最大值2147483647
    //最小整数为-2147483648
 
最后自己运行没问题,提交却报>_<,不明白啊

Submission Result: Wrong Answer

 
Input: -2147483648
Output: -2147483648
Expected: 0

 

 看了看网上的,直接用long long再直接判断倒是很简单,计算时就不用担心int越界的问题,最后加以判断就好了
 int 
reverse(int x) {
02         bool sign = x > 0 ? false : true;
03         long long temp = x;
04         long long result = 0;
05         
06         temp = temp > 0 ? temp : -temp;
07         while(temp) {
08             result *= 10;
09             result += temp % 10;
10             temp = temp / 10;
11         }
12         
13         if(result > 2147483647 || (sign && result > 2147483648))  {
14             return 0;
15         }
16         else {
17             if(sign) {
18                 return -(int)result;
19             }
20             else {
21                 return (int) result;
22             }
23         }
24 }
      
 
 
posted @ 2015-10-17 11:01  锄,禾日当午  阅读(143)  评论(0编辑  收藏  举报