c++ one line solution by calculating overlapped area


  • 0
    L

    Against integer limit overflow, check overlapping or not before calculating overlapped area.

    class Solution {
    public:
        int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            return (A<G&&E<C&&B<H&&F<D ? -(min(C,G)-max(A,E))*(min(D,H)-max(B,F)) : 0)+(C-A)*(D-B)+(G-E)*(H-F);
        }
    };
    

  • 0
    L

    In addition, the overlapped area should probably be subtracted first, because the addition may overflow. The minus overlapped area won't overflow, otherwise total area will also overflow.


Log in to reply
 

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