Contents

Chicken Coupon (with.Java)

   May 21, 2024     2 min read

This is an article about the “Chicken Coupon (with.Java)” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

When you order chicken, Programmer’s Chicken issues one coupon per chicken.

If you collect ten coupons, you can receive one free chicken, and a coupon will also be issued for the service chicken.

When the number of chickens ordered chicken is given as a parameter, complete the solution function to return the maximum number of served chickens that can be received.

Restrictions

  • chicken is an integer.
  • 0 ≤ chicken ≤ 1,000,000

Input/Output Example

chickenresult
10011
1,081120

My solution to the problem

class Solution {
 public int solution(int chicken) {
 int answer = 0;

 while (chicken >= 10) {
 answer += chicken / 10;
 chicken = chicken / 10 + chicken % 10;
 }
 return answer;
 }
}

Solution review

First, we initialize the answer variable to 0.

Use a while loop to iterate only if the number of chickens is 10 or more.

Add 10 divided by the current number of chickens to the answer. This is the number of coupons you can get from the current number of chickens.

Update the number of the next chicken by adding the remainder of dividing the number of chickens by 10 to the quotient of dividing the number of chickens by 10.

By doing this, the number of chickens purchased at one time and the number of chickens received as a coupon are added to calculate the number of chickens in the next step.

When the while loop ends, the number of chickens is less than 10, so the function returns the last calculated answer value.