Hacker Rank problem “Chocolate Feast”

I have uploaded a problem and solution that involves counting chocolates as you eat them, the tricky part is that as you eat a chocolate you get more. The general goal is to count the overall chocolates that you consume. I liked solving this problem because it has some small tricky points in the logic but the answer isn’t very lengthy. Watch the video to see a more in depth explanation of the problem and a way to come to a solution.

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

int T = in.nextInt();

if (1 > T || T > 1000) {
in.close();
return;
}

for (int i = 0; i < T; i++) {
// money given
int N = in.nextInt();

// price of a chocolate
int C = in.nextInt();

// wrappers needed for a free chocolate
int M = in.nextInt();

int chocolates = N / C;

int wrappers = chocolates;

while (wrappers >= M) {
int newChocoloate = wrappers/M;
chocolates += newChocoloate;
wrappers = wrappers % M;
wrappers += newChocoloate;
}

System.out.println("" + chocolates);
}
}
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers