這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
馬上寫了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:
- The area of the rectangular web page you designed must equal to the given target area.
- The width W should not be larger than the length L, which means L >= W.
- 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:
- The given area won't exceed 10,000,000 and is a positive integer
- 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}