首页 > 代码库 > 7. Reverse Integer

7. Reverse Integer

Reverse digits of an integer.

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

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

 

反转数字,根据数字的特性 

比如 4321的反转 1234 = (((1*10 + 2 )*10)+3)*10+ 4  

 

class Solution {public:    int reverse(int x) {        long long y = 0;        int mark = 0;        if (x < 0) x = -x,mark = 1;        while(x > 0) {            y *= 10;            y += x % 10;            x /= 10;            if (y > INT_MAX) return 0;         }        //cout<<((1<<31) - 1)<<" "<<INT_MAX<<endl;        if (mark) return - y;        return y;    }};

 

7. Reverse Integer