馬上寫了30道題目了扛点,使用golang寫起題目來代碼簡潔明了,還可以非常方便的寫測試用例岂丘,加上Goland可以進行調(diào)試陵究,有如神助。
但無論如何奥帘,寫了測試就會依賴測試判斷對錯铜邮,用了debug就會依賴debug來尋找出錯的地方,這些其實都是自己大腦偷懶把壓力推到了測試和工具上寨蹋,在日常開發(fā)上可以這樣提高代碼質(zhì)量和工作效率松蒜,但是在筆試面試時基本上不會用編譯器調(diào)試代碼,更別說寫測試用例了已旧。
因此秸苗,之后如果能直接把題目解出來,就不寫測試用例了运褪,我也示ァ(寫)時(煩)間(啦)嘛。
題目
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嗦枢,再進行相同的判斷
注意
有人覺得根可以作為寬度遞減判斷攀芯,也可以作為長度遞增判斷。但是考慮到求平方根后有可能得到小數(shù)文虏,如果將根轉(zhuǎn)換為int后侣诺,l < (area/l), 與實際不符,因此平方根應(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
}