Ponchimeow/Practice

沙之國

Opened this issue · 0 comments

Lidemy,OJ 沙之國

  1. 想像從最大的水桶依序開始裝
  2. count 計算水桶數
  3. tmp 設為目前剩餘水量
  4. 裝好的水桶放置一旁,計算水桶數與扣除已裝水量
  5. 直到剩餘水量能整除水桶大小,表示裝完
  6. 計算並回傳水桶數即為最小需裝水次數
 function pd(P) {
  const water = [1, 3, 9, 27];
  let tmp = P;
  let count = 0

  for (let i = water.length - 1; i >= 0; i -= 1) {
    if (tmp % water[i] === 0) {
      count += tmp / water[i];
      return count;
    } if (tmp / water[i] > 1) {
      const time = Math.floor(tmp / water[i]);
      tmp -= time * water[i];
      count += time;
    }
  }
}