马上写了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_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
}