Contents

The first negative number that comes up (with.Java)

   Sep 22, 2023     1 min read

In this article, First negative number to appear (with.Java)

coding test problem, we’ll do a retrospective on the problem we solved and explore other ways to solve it.

Let’s start with the problem

Problem

Complete the solution function so that, given a list of integers num_list, it returns the index of the first negative number that occurs. If there is no negative number, return -1.

Example input and output
num_listresult
[12, 4, 15, 46, 38, -2, 15]5
[13, 22, 53, 24, 15, 6]-1

My solution to the problem

class Solution {
    public int solution(int[] num_list) {
        int answer = 0;
        for(int i = 0; i < num_list.length; i++){
            if(num_list[i] < 0){
                answer = i;
                break;
            } else answer = -1;
        }
        return answer;
    }
}
Solution Description

int answer = 0;: Initialize the variable answer to store the result to be returned. answer is initialized to 0, which is the default value when no negative value is found.

for(int i = 0; i < num_list.length; i++): Iterate over the array num_list, checking each element.

if(num_list[i] < 0): Checks if the current element is negative.

answer = i;: If a negative value is found, store the current index i in answer and end the loop.

break;: Terminate the loop if a negative value is found.

else answer = -1;: If no negative value is found, set answer to -1. This indicates when no negative values are found in the array.

return answer;: Finally, return answer. This is the index of the first negative value found in the array, or -1 if no negative values are found.