Solution in C with overflow check.


  • 0
    S

    Reverse integer with simple overflow check.

    int reverse(int x) 
    {
        int tempValue = x; 
        int modValue; 
        int prevValue;     
        int reverseValue = 0;
        int negFlag = 0; 
    
        // Handle negative numbers
        if(x < 0)
        {
            negFlag = 1; 
            tempValue = -tempValue; 
        }
        
        while(tempValue != 0)
        {
            modValue = tempValue % 10; 
            reverseValue = reverseValue*10 + modValue;    
         
            // If the reversed value from previous loop doesn't match
            // with current loop (modulo value subtracted & div by 10, 
            // then it indicates overflow in conversion. 
            if((reverseValue - modValue)/10 != prevValue)
                return 0; 
            
            prevValue = reverseValue;             
            tempValue /= 10; 
        }
    
        // Add -tive sign based on the negative input check. 
        return (negFlag == 1) ? -reverseValue : reverseValue; 
    }
    
    

Log in to reply
 

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