Hackerrank Bon Appétit (C++)

C++ :

void bonAppetit(vector<int> bill, int k, int b) {
    int billToSplit = 0;
    string toPrint = "";

    for(int i = 0; i < bill.size(); i++){
        if(i != k){
            billToSplit += bill[i];
    billToSplit /= 2;

    if(billToSplit == b){
        toPrint = "Bon Appetit";
        int difference = b - billToSplit;
        toPrint = to_string(difference);

    cout << toPrint << endl;


The for loop sums up all elements of the vector bill except the element at k and put it in billToSplit. billToSplit is then divided by Brian and Anna. After that, it is compared to b (sum Anna paid Brian for her share). If it’s correct, print Bon Appetot, otherwise, get the difference that Brian must pay Anna back in difference variable, convert it into a string, and print.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *