Simple solution, beats 93% submissions


  • 1
    S

    Steps followed -

    1. Convert the integer to a string
    2. Treat it as a string reversal problem
    3. Use XOR logic to efficiently reverse the string
    4. Return string as int
    5. Take care of exceptions using a try/catch block, returning 0 in all invalid cases
    #include<string>
    
    using namespace std;
    
    class Solution {
    public:
        int reverse(int x) {
            string str = to_string(x);
            int i,j,res,sign;
            if(str[0] == '-')
                sign = -1;
            else
                sign = 1;
            for(i = 0, j = str.size() - 1; i<j;i++,j--){
                str[i] ^= str[j];
                str[j] ^= str[i];
            }
            for(i = 0, j = str.size() - 1; i<j;i++,j--){
                str[i] ^= str[j];
            }
            try {
                res = stoi(str);
            }
            catch(exception& e){
                 res = 0;
            }
            return sign*res;
        }
    };
    

  • 2
    S

    Checking for the 0th bit is essential to keep track of the sign of the integer


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.