close

題目

  For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

1. The area of the rectangular web page you designed must equal to the given target area.

2. The width W should not be larger than the length L, which means L >= W.

3. The difference between length L and width W should be as small as possible.

You need to output the length L and the width W of the web page you designed in sequence.

題意

  找出長方形的長和寬,可以想成因數的問題。

想法

  一開始打算用 array 存所有因數,但是遇到困難;後來想想好像不需要額外的 array,若遇到因數直接記錄他們的差值,被最小的存下來即可。

步驟

  1. 找出因數

  2. 計算差值並記錄

  3. 重複 1 ~ 2

程式碼

  int* constructRectangle(int area, int* returnSize) {
    int *ret;
    int i;
    int tmp;
    int save;
    int min=10000000;
    ret = malloc((int)sizeof(int)*2);
    for(i=1; i<=area; i++){
        if(area%i==0){
            tmp=abs(i-area/i);
            if(min>tmp){
                save=i;
                min=tmp;
                ret[0]=area/i;
                ret[1]=i;
            }
        }
    }
    *returnSize=2;
    return ret;
}

 

arrow
arrow
    文章標籤
    LeetCode
    全站熱搜
    創作者介紹
    創作者 Davis 的頭像
    Davis

    Epoch

    Davis 發表在 痞客邦 留言(0) 人氣()