Contents

Find an integer (with.Java)

   Nov 26, 2023     1 min read

This is the ā€œFind an integerā€ problem.

Weā€™re going to learn about it by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Letā€™s start with the problem

Problem

Given a list of integers num_list and an integer n to be found, complete the solution function so that it returns 1 if n is in num_list and 0 otherwise.

Example input and output

num_listnresult
[1, 2, 3, 4, 5]31
[15, 98, 23, 2, 15]200

My solution to the ### problem

class Solution {
    public int solution(int[] num_list, int n) {
        int answer = 0;
        for(int temp: num_list){
            if(temp == n){
                answer = 1;
            }
        }
    } return answer;
}

solution description

int answer = 0;: Initialize an integer variable, answer, to store the result. The initial value is 0.

for(int temp : num_list) : Iterates over the integer array num_list, examining each element temp.

if(temp == n) : If the current element temp is equal to n received as input:

Set answer to 1.

return answer; : Returns the value of answer representing the result of the judgment.