C solution, overflow free


  • 0
    L

    Return -1 in the case of overflow

    #define max(a, b) (((a) >= (b)) ? (a) : (b))
    #define min(a, b) (((a) >= (b)) ? (b) : (a))
    
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            int tmp1, tmp2, tmp3, tmp4;
    	long rec1Area, rec2Area, res = 0;
    
    	rec1Area = (long)(C - A) * (D - B);
    	if(rec1Area > INT_MAX) return -1;
    	rec2Area = (long)(G - E) * (H - F);
    	if(rec2Area > INT_MAX) return -1;
    	res = rec1Area + rec2Area;
    	if(((A <= G) && (E <= C)) && ((D >= F) && (H >= B))) {//overlapping
    		tmp1 = max(A, E);
    		tmp2 = min(C, G);
    		tmp3 = min(D, H);
    		tmp4 = max(B, F);
    		res = res - (tmp2 - tmp1) * (tmp3 - tmp4);
    		if(res > INT_MAX) return -1;
    		return (int)res;
    	}
    	if(res > INT_MAX) return -1;
    	return (int)res;
    }
    

Log in to reply
 

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