Find an integer (with.Java)
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_list | n | result |
---|---|---|
[1, 2, 3, 4, 5] | 3 | 1 |
[15, 98, 23, 2, 15] | 20 | 0 |
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.