How to calculate the handle number for reverse integer


  • 0
    A
    class Solution {
    public:
        int reverse(int x) {
            int a[32];
            int x_out = 0;
            int t;
            int count = 0;
    			if(x < 0){
    				t = 0 - x;
    			}else{
    				t = x;
    			}
    			while(t != 0)
    			{
    				count++;
    				t = t / 10;
    			}
    			count --;
    			t = x;
    			for(int i = 0; i <= count; i ++){
    					a[i] = '\0';
    			}
    			for(int i = count; i >= 0; i--){
    					a[i] =  t % 10;
    					t = t/10;
    			}       
    			for(int i = 0 ; i <= count; i ++){  
    					x_out += a[i]*pow(10.00, i);
    					if (x_out >= pow(2.00, 32-1) || x_out <= -pow(2.00, 32-1) ) {
                            return 0;
                        }
    			}
    
    
    	        return x_out;
        }
    };
    

    Here is my code and it is accepted, but my way is pretty stupid. I just want to know how to calculate the biggest/smallest number to identify the overflow/underflow
    for example:
    if my code is:

    int out = 0;         
    while (t != 0) {
        out =out*10 + x%10;
        x = x/10;
    }
    return out;
    

    there should be a handle overflow/underflow, like:

     if (Math.abs(out) > the_number_IDK) {
             return 0;
     }
    

    so what value is the "the_number_IDK" ?
    Thanks a lot!


  • 0
    N

    the range of values for integers are -2^32 to 2^31-1, i.e -4294967296 to 2147483647


Log in to reply
 

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