223. Rectangle Area
来源:互联网 发布:js遍历数组中对象 编辑:程序博客网 时间:2024/06/06 09:05
问题描述
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Assume that the total area is never beyond the maximumpossible value of int.
解题思路
该问题比较简单,题目分别给出两个长方形左下角和右上角的坐标值,要求我们求出两个长方形覆盖的总面积。思路很简单,先分别求出两个长方形的面积,然后减去它们重叠部分的面积即可。但是在开始代码运行中会有一个问题,测试的时候显示答案错误。代码中第24行辅助函数中如果直接判断w和h 的值与0 的大小,会溢出报错。所以要用w1和w2以及h1和h2直接比较。
代码展示
#include<iostream>#include<math.h>using namespace std;class Solution {public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int a1 = (C - A) * (D - B); int a2 = (G - E) * (H - F); int comarea = com_area(A, B, C, D, E, F, G, H); int result = a1 + a2 - comarea; return result; } int com_area(int A, int B, int C, int D, int E, int F, int G, int H){ int w1 = max(A, E); int w2 = min(C, G); int w = w2 - w1; int h1 = max(B, F); int h2 = min(D, H); int h = h2 -h1; if(h2 < h1 || w2 < w1) return 0; else return w * h; }};int main(){ int A, B, C, D, E, F, G, H; cout<<"请依次输入 A B C D E F G H的值:"; cin>>A>>B>>C>>D>>E>>F>>G>>H; Solution solution; int result = solution.computeArea(A, B, C, D, E, F, G, H); cout<<"总面积为:"<<result<<endl; return 0; }
运行结果展示
阅读全文