D111 492. Construct the Rectangle

Topic link

492. Construct the Rectangle

Subject analysis

Given the area of the rectangle, find the side length with the smallest difference in width and height.

Train of thought

Because we’re trying to figure out the area, we’re going to take the square root of SQRT, and we’re going to take the whole thing down. And then we decrease, and we try to see if the remainder is 0 when we divide the area by the length of the sides, or divisible.

Why start with the value after the square root? Because they want the difference between the width and the height to be as small as possible.

The final code


      
class Solution {

    / * * *@param Integer $area
     * @return Integer[]
     */
    function constructRectangle($area) {
        $mid = floor(sqrt($area));
        for($i=$mid; $i>1; $i--){
            if($area%$i == 0) {return[$area/$i, $i]; }}return [$area, 1]; }}Copy the code

If you find this article useful, you are welcome to subsidize it with love.