Thursday, 8 June 2017

Reverse Integer (LeetCode)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    int reverse(int x) {
        
        bool flag = false;
        if(x<0)
        {
            flag = true;
            x*=-1;
        }
        int rev = 0;
        while(x)
        {
            if((rev*10)/10 != rev) return 0; // checking overflow
            rev = rev*10 + x%10;
            x/=10;
        }
        
        if(flag) rev*=-1;
        
        return rev;
    }
};

No comments:

Post a Comment