Solution in C#


  • 0
    L

    There are two points to caveats

    1. The negative sign
    2. The maximum and minimum of integer

    Steps:

    1. We should judge x equals -2147483648, if true, the result is 0
    2. Get the absolute value of x
    3. The loop
      If rex * 10 + rightmost larger than maximum value of integer, return 0.
      We can get the rightmost value with x%10
      The remaining value is x/10

    Return the res with plus or minus sign

    public class Solution {
        public int Reverse(int x) {
            // If the x equals  -2147483648 , return 0
            if(x == int.MinValue)
            {
                return 0;
            }
            
            // Get the value either x is positive or negative
            int num = Math.Abs(x);
            // Set the result 0
            int res = 0;
            while(num != 0)
            {
               // If the res will larger than 2147483647, return 0
                if(res > (int.MaxValue - num%10)/10)
                {
                    return 0;
                }
                // Calculate the res
                res = res * 10 + num % 10;
               // Get the next num
                num = num / 10;
            }
            return x>0?res:-res;
        }
    }
    

Log in to reply
 

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