n보다 커질 때까지 더하기

김윤하·2023년 12월 13일
0

CodingTest

목록 보기
22/27
post-thumbnail

문제 설명

정수 배열 numbers와 정수 n이 매개변수로 주어집니다. numbers의 원소를 앞에서부터 하나씩 더하다가 그 합이 n보다 커지는 순간 이때까지 더했던 원소들의 합을 return 하는 solution 함수를 작성해 주세요.

제한사항

1 ≤ numbers의 길이 ≤ 100
1 ≤ numbers의 원소 ≤ 100
0 ≤ n < numbers의 모든 원소의 합

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

0개의 댓글

Powered by GraphCDN, the GraphQL CDN