All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0401_0500.s0492_construct_the_rectangle.Solution Maven / Gradle / Ivy

There is a newer version: 1.24
Show newest version
package g0401_0500.s0492_construct_the_rectangle;

// #Easy #Math

public class Solution {
    /*
      Algorithm:
     - start with an index i from the square root all the way to 1;
     - if at any time, area % i == 0 (so i is a divisor of area), then it's the closest solution.
    */
    public int[] constructRectangle(int area) {
        int low = (int) Math.sqrt(area);
        while (low > 0) {
            if (area % low == 0) {
                return new int[] {area / low, low};
            }
            low--;
        }
        return new int[] {0, 0};
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy