[LeetCode] 7 - Reverse Integer

Reverse digits of an integer.

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

 

class Solution {
public:
  int reverse(int x) {
    int res = 0;
    int x0 = x;
    int x1;
    while (x0) {
      x1 = x0 % 10;
      x0 = x0 / 10;
      if (res > (int)(0x7fffffff)/10) {  // 如果数据发生溢出
        return 0;
      }
      if( res < (int)(0x80000000)/10 ) {
        return 0;
      }
      res = res * 10 + x1;
    }
    return res;
  }
};

posted on 2015-08-28 11:03  tuituji  阅读(100)  评论(0编辑  收藏  举报

导航