Using C# checked keyword and try-catch block for overflow exception


  • 0

    I don't know if using checked is cheating, Here's my code in C#:
    The idea is simple: We just want the actual result, if the reversed int can not be represented in int range, just throw exception. Other than that just keep puting the last digit to the front. Pretty straightforward. O(n) time and O(1) space.

        public int Reverse(int x) {
            try
            {
                int result = 0;
                while(x!=0)
                {
                    result = checked( result * 10 + x % 10);
                    x = x / 10;
                }
                return result;
            }
            catch(Exception)
            {
                return 0 ;
            }
        }
    

Log in to reply
 

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