C# Solution to ReverseInteger


  • 0
    F

    The optimal solution in space is checking that we can do the operation given the Int32 constraint.

    Solution code:

     public int Reverse(int x)  {
                int result = 0; 
                while (x != 0)
                {
                    if (!legalOperation(result, x % 10))
                        return 0;
                    
                    result = result * 10 + (x % 10);                
                    x = x / 10;
                }
            return result;
        }  
    

    Legal operation

    Every time we increment the counter, we have the risk of an overflow. The operation we are doing is:

                result = result * 10 + (x % 10);
    

    For an optimal solution we need to check that the above operation does not overflow. Naming x%10 as "D" and given "result" as an Int32, we want:

    Int32.MaxValue >= result * 10 + D  if the input is a positive number
    
    Int32.MinValue <= result * 10 + D if the input is a negative number.
    

    These conditions make sure that result * 10 + D can be saved in the Int32 variable. So "solving equations" we have,
    for positive input:

    result <= (Int32.MaxValue - D) / 10
    

    for negative input:

    result  >= (Int32.MaxValue - D) / 10
    

    Which let's us define the "legalOperation" check:

    public bool legalOperation(int x, int digit)
            {
                if (x > 0)
                    return (x <= (Int32.MaxValue - digit) / 10); // if true, yes you can do x*10+digit
                else if (x < 0)
                    return (x >= (Int32.MinValue - digit) / 10);                                   
                return true;
         }   
    

Log in to reply
 

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