포스트

N보다 커질 때까지 더하기

https://school.programmers.co.kr/learn/courses/30/lessons/181884

문제

  • 문제 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
    public int solution(int[] numbers, int n) {
        int sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
            if (sum > n) {
                return sum;
            }
        }
        return sum; // numbers의 모든 원소를 다 더한 경우
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.solution(new int[]{34, 5, 71, 29, 100, 34}, 123)); // 출력: 139
        System.out.println(sol.solution(new int[]{58, 44, 27, 10, 100}, 139)); // 출력: 239
    }
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.