Reverse Integer (C++)


  • 0
    M

    Below is the simple solution in C++ to reverse a given integer, It covers all test cases.

    '''
    class Solution {
    public:
    int reverse(int x) {

        long result=0,negative=0;
        
        if(x<0)
        {
            negative=1;
            x=x*(-1);
        }
            
        while(x>0)
        {
            result=(result*10)+(x%10);
            x=x/10;
        }
        
        if(result>2147483647)
            return 0;
        
        if(negative==1)
            result=result*(-1);
        
        return result;    
    }
    

    };
    '''


Log in to reply
 

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