7 line C# simple solution explained


  • 0

    Use a long to detect overflow simply check if the long value has passed the allowed range of a 32 bit int. The heart of the problem is in the line res = (x % 10) + (res * 10) which builds the reversed value digit by digit. This line of code pulls the least significant digit from x and shifts our current accumulated res one digit over finally adding the results together. the x is then divided by 10 to get rid of the least significant digit since we have already accommodated this digit in our reversed integer.

    public int Reverse(int x) {
            long res = 0;
            while(x != 0){
                res = (x % 10) + (res * 10);
                if(res > Int32.MaxValue || res < Int32.MinValue) return 0;
                x /= 10;
            }
            return (int)res;
    }

Log in to reply
 

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