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; }

运行结果展示
这里写图片描述

这里写图片描述

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 过隙 隙组词 隙拼音 隙怎么读 隙的拼音 腔隙脑梗死 隙组词语 隙成语 隙的组词 隙词语 病隙碎笔 隙的成语 隙怎么组词 隙字组词 腔隙性脑梗死能活几年 批隙导窾 隙组词和拼音 脑腔隙灶 什么过隙成语 腔隙灶 腔隙性脑梗死什么意思 白马过隙 腔隙脑梗死能自愈吗 可乘之隙 隙的词语 腔隙性脑梗死严重吗 一隙不通 隙读音 无隙可乘 隙可以组什么词 腔隙性脑梗死能恢复吗 隙穴之窥 白什么什么隙成语 多发腔隙性脑梗死严重吗 乘间投隙 叶隙间的阳光作品 我的二次元之旅 叶隙间的阳光 障刀 障壁 大柱山隧道