Leet - 7

Having fun on Leetcode with C++, Java, Python & GO

Problem 7. Reverse Integer

My attempt(s)

Code

C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
    int reverse(int x) {
        string s = to_string(x);
        string temp="";
        
        for (int i=s.length()-1;i>=0;i--)
        {
            temp=temp+s[i];
        }
        
        if (x<0)
        {
            try
            {
                x=stoi(temp);
            }
            catch (std::out_of_range&)
            {
                return 0;
            }
            x=x*-1;
        }
        else
        {
            try
            {
                x=stoi(temp);
            }
            catch (std::out_of_range&)
            {
                return 0;
            }
        }
            
        return x;
        
    }
};

Explanation of idea

Good solution ref.

Code

C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

Analysis

Licensed under CC BY-NC-SA 4.0