[LeetCode By Go 29]492. Construct the Rectangle

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

馬上寫了30道題目了,使用golang寫起題目來代碼簡潔明了,還可以非常方便的寫測試案例,加上Goland可以進行調試,有如神助。
但無論如何,寫了測試就會依賴測試判斷對錯,用了debug就會依賴debug來尋找出錯的地方,這些其實都是自己大腦偷懶把壓力推到了測試和工具上,在日常開發上可以這樣提高代碼品質和工作效率,但是在筆試面試時基本上不會用編譯器調試代碼,更別說寫測試案例了。
因此,之後如果能直接把題目解出來,就不寫測試案例了,我也省(寫)時(煩)間(啦)嘛。

題目

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.

Example:

Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.

Note:

  1. The given area won't exceed 10,000,000 and is a positive integer
  2. The web page's width and length you designed must be positive integers.

解題思路

求面積的平方根,然後將根作為寬度w,如果area能整除w,則l=area/w, 否則w減1,再進行相同的判斷
注意
有人覺得根可以作為寬度遞減判斷,也可以作為長度遞增判斷。但是考慮到求平方根後有可能得到小數,如果將根轉換為int後,l < (area/l), 與實際不符,因此平方根應該作為寬度

代碼

constructRectangle.go

package _492_Construct_the_Rectangleimport "math"func constructRectangle(area int) []int {    var ret []int    sqrtArea := math.Sqrt(float64(area))    var w int    w = int(sqrtArea)    for ; w > 0; w-- {        if area % w == 0 {            l := area / w            ret = []int{l, w}            break        }    }    return ret}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.