Make Be BackEnd

[JAVA] n보다 커질 때까지 더하기 본문

코딩테스트/프로그래머스

[JAVA] n보다 커질 때까지 더하기

Initsave 2024. 3. 10. 09:26

 

 

 

 

 

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

 

 

 

 

 

 

 

 

import java.util.Arrays;

class Solution {
    public int solution(int[] numbers, int n) {
        return Arrays.stream(numbers).reduce(0, (acc, i) -> n >= acc ? acc + i : acc);
    }
}

 reduce !!

 

 

 

 

https://download.java.net/java/GA/jdk14/docs/api/java.base/java/util/stream/Stream.html#reduce(java.util.function.BinaryOperator)

 

Stream (Java SE 14 & JDK 14)

Type Parameters: T - the type of the stream elements All Superinterfaces: AutoCloseable, BaseStream > public interface Stream extends BaseStream > A sequence of elements supporting sequential and parallel aggregate operations. The following example illustr

download.java.net