Easy to understand C# with checked operator to check for overflows


  • 0
    C

    public class Solution {

    public int GetDigitAt(long num, int index)
    {
        return Convert.ToInt16(
                Math.Floor((num % Math.Pow(10, index)) / Math.Pow(10, index-1)
            ));
    }
    
    public int Reverse(int x) {
        try
        {
            // we make the compiler check forcefully if the overflow happened
            int abs = checked(Math.Abs(x));
            Console.WriteLine(abs);
            
            // cool guy way of getting length of a number
            var length = (int)(Math.Floor(Math.Log10(abs)) + 1);
            
            var result = 0;        
            
            // base is reversed and starts at 1 to length + 1
            for (int i=1, j=length; i <= length; i++)
            {
                var digit = GetDigitAt(abs, i);
                result = checked(result + (int)(digit * Math.Pow(10, --j)));
            }        
    
            // don't forget to add the negative sign back
            if (x < 0)
            {
                return result * -1;
            }
            
            return result;
        
        } 
        catch (OverflowException ex)
        {
            // catch the overflows you are checking for and return 0
            return 0;
        }
    }
    

    }


Log in to reply
 

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