프로그래머스 : 정수 찾기

Digeut·2023년 12월 10일
0

프로그래머스

목록 보기
121/164

❔문제설명

정수 리스트 num_list와 찾으려는 정수 n이 주어질 때, num_list안에 n이 있으면 1을 없으면 0을 return하도록 solution 함수를 완성해주세요.

🤔아이디어

for문과 if문을 같이 사용하면 되는거 아닐까

❌틀린코드

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

🙄오류


왜 0만 나올까. 왜 0만...

-> 반복문을 돌면서 answer의 값이 자꾸 덧씌워진다!!!!!
마지막까지 돌면 그냥 0이 나올수 밖에 없구나
조건을 만족하면 break를 해야한다!!

💡코드풀이

class Solution {
    public int solution(int[] num_list, int n) {
        int answer = 0;
        for(int i = 0 ; i < num_list.length ; i++){
            if(num_list[i] == n){
                answer = 1;
                break;
            }
        }
        return answer;
    }
}
profile
개발자가 될 거야!

0개의 댓글