Thứ Hai, 16 tháng 5, 2016

Luyện lập trình


  1. makeBricks
Link: http://codingbat.com/prob/p183562

Problem:
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return true if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops.

makeBricks(3, 1, 8) → true
makeBricks(3, 1, 9) → false
makeBricks(3, 2, 10) → true

Answer 1:

public boolean makeBricks(int small, int big, int goal) {
  for (int i = 0; i <= big; i++) {
    if (i * 5 <= goal && i * 5 + small >= goal)
      return true;
  }
  return false;

}

Answer 2:

public boolean makeBricks(int small, int big, int goal) {
  int smallNum = goal % 5; // minimum number of small bricks
  int bigNum = goal / 5;  // maximum number of big bricks
  
  // cannot supply minimum number of small bricks
  if (smallNum > small)
    return false;
  
  // can supply minimum number of small bricks
  // and maximum number of big bricks
  if (bigNum <= big)
    return true;
  
  // must reduce number of big bricks
  // and increase number of small bricks
  if ((bigNum - big) * 5 + smallNum > small)
    return false;
  
  return true;

}

Không có nhận xét nào:

Đăng nhận xét