7. Reverse Integer

Reverse digits of an integer.

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

当溢出时,返回0.

参考代码:

class Solution {
public:
    int reverse(int x) {
        int result = 0;

        while(x){
            int temp = result*10+x%10;
            x /= 10;
            if(temp/10!=result){
                result = 0;
                break;
            }
            else result = temp;
        }

        return result;

    }
};

判断两个数相乘是否溢出:乘上后再除回来,和原数相同则没有溢出。
判断两个数相加是否溢出:

//无符号整数相加

int uadd_ok(unsigned x, unsigned y)

{

   unsigned z = x + y;

   if(z < x)

      return 0;

    return 1;

}

//有符号整数相加

int add_ok(int x, int y)

{

   int z = x + y;

   if(x > 0 && y > 0 && z < 0)

      return 0;  

   if(x < 0 && y <  0 && z > 0)

      return 0;

    return 1;

}

你可能感兴趣的:(7. Reverse Integer)