[演算法題目] Water Bottles

本題資訊

難度:easy
使用語言:C++


題目敘述

There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.

The operation of drinking a full water bottle turns it into an empty bottle.

Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.

題目和小時候遇到的數學問題幾乎一樣。

Idea

其實這題很簡單,但我面試的時候曾經被這一題纏住XD 原因是我不太清楚整數的除法會不會出錯,以及太執著於紀錄回數、又忘記可以好好利用餘數,會特別紀錄這簡單的一題主要是給自己做個恥辱的紀念 QQ

我們利用 sum 紀錄可以喝的總瓶數,一開始我們一定喝了 numBottles,所以 sum 初始值就直接先設定上去。再來 exchange 是紀錄中間兌換的瓶數。

只要我們手上的瓶子大於等於 numExchange,就可以不停兌換。exchange 的資料型態是整數,所以手上的瓶子除以 numExchange 就會是空瓶所兌換到的瓶數,sum 記得要把這個瓶數加上去。另外還有其他沒有被換到的空瓶,也要列入下一次的計算裡面,這裡就利用餘數加上 exchange 就可以了!

using namespace std;

int numWaterBottles(int numBottles, int numExchange) {
  int sum = numBottles;
  int exchange;
  
  while (numBottles >= numExchange){
    exchange = numBottles / numExchange;
    sum += exchange;
    numBottles = (numBottles % numExchange) + exchange;
  }
  return sum;
}

雖然簡單,但想到那時候沒有寫出來還是好難過 QQ

讓我知道你在想什麼!

Picture of ALEX

ALEX

藍白拖愛好者,一事無成話偏多

Recent Posts

C++

NLP