LeetCode #7 Reverse Integer

来源:互联网 发布:2017天猫数据直播 编辑:程序博客网 时间:2024/06/03 21:24

Description

Reverse digits of an integer.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


Example1

x = 123, return 321
x = -123, return -321


Analysis

题目难度为:Easy
这道题目的难点其实在于边界条件的检测,上界是2147483647(2的31次方-1),下界是-2147483648,倒转之后分别是7463847412和-8463847412,我们可以看到,如果后面9位都是463847412。一个数x,如果大于10位肯定溢出,小于10位肯定不溢出,所有只需要判断当x是一个10位整数的情况,并且输入的数都要是合法的,所有只需要判断后面9位就可以了。


Code(c )

class Solution {public:    int reverse(int x) {        if (overflow(x)) return 0;        bool is_pos = x >= 0;          x = abs(x);        stringstream stream;        stream << x;        string s;        stream >> s;        int i=0, j=s.size()-1;        while(i<j)        {            swap(s[i], s[j]);            i++;            j--;        }        x = atoi(s.c_str());        if (is_pos) return x;          else return -x;    }    bool overflow(int x)      {          if (x / 1000000000 == 0) {              return false;          }        else if (x == INT_MIN) {              return true;          }           x = abs(x);          for (int cmp = 463847412; cmp != 0; cmp/=10, x/=10)          {              if ( x%10 > cmp%10 )              {                  return true;              } else if (x%10 < cmp%10)              {                  return false;              }          }          return false;      }  };
0 0
原创粉丝点击