본문 바로가기
coding test/Java

프로그래머스 ) lv.0 ) 등차수열의 특정한 항만 더하기

by heidish 2023. 6. 21.
반응형

 

 

 

 

 

 

 

SOL )

class Solution {
    public int solution(int a, int d, boolean[] included) {
        int answer = 0;
        
        for (int i = 0; i < included.length; i++) {
            answer += included[i] == true ? (a + d*i) : 0;
        }
        
        return answer;
    }
}

처음에는 map을 사용해볼까 하다가, 악 key값 중복이 안되는걸 깨닫고,,,,,ㅎ 멍청이,,,,,

이중 배열을 사용해볼까 하다가, 그렇게까지 어렵게 하지 않아도 풀 수 있을것 같아서

그냥 included 배열을 for문 돌리며 그 값이 true 인 index의 등차수열 값만 더해주었다.

 

 

 

 

 

OTHER SOL )

import java.util.stream.IntStream;

class Solution {
    public int solution(int a, int d, boolean[] included) {
        return IntStream.range(0, included.length).map(idx -> included[idx]?a+(idx*d):0).sum();
    }
}

Java8 부터 사용 가능한 IntStream 을 사용하며 람다 표현식까지 사용한 풀이가 있었다.

멋찌다,,,,,,

 

 

추가로 위 코드를 보면서 참고한 링크들!

https://www.tutorialspoint.com/intstream-map-method-in-java

https://www.devkuma.com/docs/java/stream-api/int-stream/

https://isntyet.github.io/java/java-stream-%EC%A0%95%EB%A6%AC(map)/ 

 

java stream 정리(map)

Repository = java-practice

isntyet.github.io

 

 

 

반응형

댓글