7.整数反转

7. 整数反转

这题还挺有意思的哈哈,反向思维,既然不能用int64。那我就限制好边界。

class Solution {
public:
    int reverse(int x) {
      int reveredX = 0, tx = x;
      int minInt = (unsigned int)1 << 31, maxInt = ((unsigned int)1 << 31) - 1;
      while(tx) {
          if(reveredX < 0 &&  (minInt - tx%10) / 10 > reveredX ) return 0;
          else if(reveredX > 0 && (maxInt - tx%10) / 10 < reveredX) return 0;
          reveredX = tx % 10 + reveredX * 10;
          tx /= 10;
      }
      return reveredX;
    }
};

Comments