0

I'm currently working on a leetcode problem to construct a rectangle. An int value will be passed into a method, and from there I need two values for the length and width, where the length and width must be as small as possible and the L >= W. I looked at a couple solutions but cannot grasp the concept. On line 4, wouldn't the result always yield the area? So how does the for loop continue ? For instance if the area is 26, and we do the calculations on line 4, Wouldn't we always get the same number on line 4? However when I run the code, it gives the correct results of [13,2].

1    class Solution {
2    public int[] constructRectangle(int area) {
3        for(int w=(int)Math.sqrt(area);w>0;w--){
4           if((area/w)*w==area)return new int[]{area/w,w};
       }return new int[]{};
    }
 }
  • try stepping through it with the debugger. See how the values change at each step of the iteration. – experiment unit 1998X Feb 08 '23 at 01:44
  • this has to do with truncation of data (ie when you cast a double to an int) – experiment unit 1998X Feb 08 '23 at 01:47
  • *On line 4, wouldn't the result always yield the area?* Not when working with integers. Put `System.out.println(area/w + " " + w);` as the first statement in the for loop to see what is happening. Remember, int arithemetic drops fractions. – WJS Feb 08 '23 at 01:56
  • You may find [this question](https://stackoverflow.com/q/4685450) helpful. – Dawood ibn Kareem Feb 08 '23 at 02:23
  • Is there also a requirement that length and width are integers? And what does "length and width are as small as possible mean"? That their sum should be the minimum possible? – tgdavies Feb 08 '23 at 02:27
  • @tgdavies Well, it wouldn't be much of a problem if doubles were used. All the answers would be squares which is a special rectangle. – WJS Feb 08 '23 at 12:58

0 Answers0