My 4ms c solution


  • 8
    C
    int reverse(int x) {
    int px=0;
    while(x!=0)
     {
        if(px>INT_MAX/10 || px<INT_MIN/10)return 0;
        px=px*10+x%10;
        x=x/10;
    }
    return px; 
    

    }


  • 0
    C

    My similar solution as yours.

       int reverse(int x) {
            unsigned int val = abs(x);
            unsigned int result = 0;
        
            while (val) {
            	if (result > ((unsigned int)(1 << 31) - 1) / 10)
            		return 0;
        
            	result = result * 10 + val % 10;
            	val /= 10;
            }
        
            return (x > 0 ? result : (-1 * result));
        }

  • 0
    D

    Could you please tell me where the INT_MAX and INT_MIN is defined ? Thanks.


  • 0
    C

    The INT_MAX and INT_MIN is defined in limits.h,a C header files.


  • 2
    S

    Why have you done INT_MAX/10 and INT_MIN/10 instead of if(px>INT_MAX || px<INT_MIN) ? Because it returns a 0 if the integer passed is >INT_MAX/10 but <INT_MAX . Which is not right ?


Log in to reply
 

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