馬上寫(xiě)了30道題目了,使用golang寫(xiě)起題目來(lái)代碼簡(jiǎn)潔明了,還可以非常方便的寫(xiě)測(cè)試用例,加上Goland可以進(jìn)行調(diào)試,有如神助。
但無(wú)論如何,寫(xiě)了測(cè)試就會(huì)依賴測(cè)試判斷對(duì)錯(cuò),用了debug就會(huì)依賴debug來(lái)尋找出錯(cuò)的地方,這些其實(shí)都是自己大腦偷懶把壓力推到了測(cè)試和工具上,在日常開(kāi)發(fā)上可以這樣提高代碼質(zhì)量和工作效率,但是在筆試面試時(shí)基本上不會(huì)用編譯器調(diào)試代碼,更別說(shuō)寫(xiě)測(cè)試用例了。
因此,之后如果能直接把題目解出來(lái),就不寫(xiě)測(cè)試用例了,我也?。▽?xiě))時(shí)(煩)間(啦)嘛。
題目
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,再進(jìn)行相同的判斷
注意
有人覺(jué)得根可以作為寬度遞減判斷,也可以作為長(zhǎng)度遞增判斷。但是考慮到求平方根后有可能得到小數(shù),如果將根轉(zhuǎn)換為int后,l < (area/l), 與實(shí)際不符,因此平方根應(yīng)該作為寬度
代碼
constructRectangle.go
package _492_Construct_the_Rectangle
import "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
}