Beer Bottles in C++


Suppose we have one number n. Here n indicates n full beer bottles. If we can exchange 3 empty beer bottles for 1 full beer bottle, we have to find the number of beer bottles we can drink.

So, if the input is like 10, then the output will be 14.

To solve this, we will follow these steps −

  • Define a function solve(), this will take n,

  • ret := 0

  • while n >= 3, do −

    • q := n / 3

    • ret := ret + q * 3

    • n := n - q * 3

    • n := n + q

  • ret := ret + n

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(int n) {
      int ret = 0;
      while(n >= 3){
         int q = n / 3;
         ret += q * 3;
         n -= q * 3;
         n += q;
      }
      ret += n;
      return ret;
   }
};
main() {
   Solution ob;
   cout << ob.solve(10);
}

Input

10

Output

14

Updated on: 02-Sep-2020

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements