Reverse Integer


  • 0
    P

    It could be solved without an extra space, or we can use stack implementations.

    public class Solution {
        public int Reverse(int x) {
            if(x >=-9 && x <=9) return x;
           
            bool isNegative =false;
            if(x < 0)
            {
                isNegative = true;
                x = x*(-1);
            }
             
            int res = 0;
            int remaining = x;
            int mod = 0;
           
            
            while (remaining>0)
            {
                mod = remaining%10;            
                remaining = remaining/10;                    
                double checkMax = (double)res*10 + mod;
                if (checkMax >= Int32.MinValue && checkMax <= Int32.MaxValue)
                {
                    res = (int)checkMax;
                }
                else{ return 0;}
                     
            }    
            if(isNegative) res=res*(-1);
            return res;
        }
    }
    

Log in to reply
 

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