프로그래머스 : 길이에 따른 연산

Digeut·2023년 12월 15일
0

프로그래머스

목록 보기
123/164

❔문제설명

정수가 담긴 리스트 num_list가 주어질 때, 리스트의 길이가 11 이상이면 리스트에 있는 모든 원소의 합을 10 이하이면 모든 원소의 곱을 return하도록 solution 함수를 완성해주세요.

🤔아이디어

if문과 for문을 같이 사용하면될것같은데

❌틀린코드

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

🙄오류

합의 경우에는 맞게 되는데 곱셈을 하는 경우 모든 결과값이 0이 되었다.. answer이 0으로 설정되어 있으니까 뭘 곱하든 계속 0이 나오는거지...

💡코드풀이

class Solution {
    public int solution(int[] num_list) {
        int answer = 0;
        if(num_list.length > 10){
            for(int i =0 ; i < num_list.length ; i++){
                answer += num_list[i];
            }
        } else {
            answer = 1; // ⭐기본 값을 1로 설정해주었다.
            for(int i =0 ; i < num_list.length ; i++){
                answer *= num_list[i];
            }
        }
        return answer;
    }
}

약간... 잔꾀같긴한데 다른 방법은 뭐가 있을까...

ChatGPT에 물어봤는데도 나랑 같은 결과를 내뱉는다. 이게 맞는거야?

profile
백엔드 개발자 지망생

0개의 댓글