Contents

Sharing a Pizza 1 (with.Java)

   Jan 5, 2024     1 min read

This is a recap of the “Share a Pizza 1” problem.

We’re going to learn by solving coding test problems, reflecting on the problems we’ve solved, and exploring other ways to solve them.

Let’s start with the problem.

Problem

A pizza parlor cuts a pizza into seven slices.

Given the number of people to share the pizza, n, complete a solution function that returns the number of slices needed to ensure that everyone gets at least one slice.

Example input and output

nresult
71
11
153

My solution to the ### problem

class Solution {
    public int solution(int n) {
        int answer = 0;
        if(n % 7 == 0){
            answer = n / 7;
        }else{
            answer = n / 7 + 1;
        }
        return answer;
    }
}

Solution Description

public int solution(int n) : Declares a function solution, which takes a positive integer n as an input parameter. The function returns an integer value.

int answer = 0;: Declares the integer variable answer and initializes it to 0. This variable will store the result.

if (n % 7 == 0): If the input integer n is divided by 7 and the remainder is 0, that is, if n is a multiple of 7, perform the following operation.

answer = n / 7;: store the quotient of n divided by 7 in the variable answer. This way, if it is a multiple of 7, the quotient represents the exact value.

else: If it is not a multiple of 7, that is, if n is not a multiple of 7, do the following

answer = n / 7 + 1;: Store the quotient of n divided by 7 plus 1 in the answer variable. This will represent the remainder, if any, rounded up to the next integer.

return answer;: Returns the final result, the value answer, as the return value of the function.