Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
#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
Advertisements
