[알고리즘문제풀기] 짝수의 합

silver's avatar
Nov 17, 2024
[알고리즘문제풀기] 짝수의 합
 

문제

 

내가 작성한 정답

class Solution { public int solution(int n) { int answer = 0; for(int i=2; i<=n; i+=2 ){ answer += i; } return answer; } }
class Solution { public int solution(int n) { int answer = 0; for(int i=1; i<=n/2; i++ ){ answer += 2*i; } return answer; } }
 

다른 사람들이 작성한 정답

import java.util.stream.IntStream; class Solution { public int solution(int n) { return IntStream.rangeClosed(0, n) .filter(e -> e % 2 == 0) //숫자 리스트에서 짝수만 골라낸다. .sum(); } }
 
💡

IntStream.range와 IntStream.rangeClosed는 주어진 범위 내 순차적인 정수 스트림을 반환한다.

IntStream.range(1, 5).forEach(System.out::println); //출력: 1234 IntStream.rangeClosed(1, 5).forEach(System.out::print); // 출력: 12345
 

IntStream은 기본형 int를 다루는 스트림으로, 숫자 데이터를 쉽게 처리할 수 있도록 다양한 메서드를 제공한다.

숫자 생성: range, rangeClosed
필터링: filter, distinct
변환: map, boxed
계산: sum, average, reduce, max, min
정렬/출력: sorted, toArray
 
  1. range( int startInclusive,int endExclusive) :startInclusive부터 endExclusive 직전까지의 숫자를 생성
  1. rangeClosed(int startInclusive, int endInclusive) :startInclusive부터 endInclusive 포함까지의 숫자를 생성
  1. filter(IntPredicate predicate) : 주어진 조건(predicate)에 맞는 숫자만 필터링
  1. map(IntUnaryOperator mapper) : 각 숫자를 변환하여 새로운 스트림을 생성
    1. IntStream.rangeClosed(1, 5) .map(n -> n * n) .forEach(System.out::println); // 출력: 1, 4, 9, 16, 25 (숫자들의 제곱)
  1. sum() : 스트림의 모든 숫자를 더한 결과를 반환
  1. max() : 스트림에서 가장 큰 값 OptionalInt로 반환.
  1. min() : 스트림에서 가장 작은 값 OptionalInt로 반환.
    1. IntStream.rangeClosed(1, 5) .max() .ifPresent(System.out::println); // 출력: 5 IntStream.rangeClosed(1, 5) .min() .ifPresent(System.out::println); // 출력: 1
  1. average() : 스트림의 숫자 평균을 계산하여 OptionalDouble로 반환.
    1. IntStream.rangeClosed(1, 5) .average() .ifPresent(System.out::println); // 출력: 3.0 (평균: (1 + 2 + 3 + 4 + 5) / 5)
  1. distinct() : 중복된 값을 제거
    1. IntStream.of(1, 2, 2, 3, 3, 3, 4) .distinct() .forEach(System.out::println); // 출력: 1, 2, 3, 4
  1. sorted() : 스트림의 숫자를 정렬
    1. IntStream.of(4, 2, 3, 1, 5) .sorted() .forEach(System.out::println); // 출력: 1, 2, 3, 4, 5
  1. boxed() : 기본형 스트림(IntStream)을 객체 스트림(Stream)으로 변환
    1. IntStream.rangeClosed(1, 5) .boxed() .forEach(i -> System.out.println(i.getClass().getSimpleName())); // 출력: Integer, Integer, Integer, Integer, Integer
  1. toArray() : 스트림의 숫자들을 배열로 반환
    1. int[] arr = IntStream.rangeClosed(1, 5).toArray(); System.out.println(Arrays.toString(arr)); // 출력: [1, 2, 3, 4, 5]
  1. reduce(int identity, IntBinaryOperator accumulator) : 스트림의 모든 숫자를 누적 계산하여 하나의 결과를 반환
    1. int product = IntStream.rangeClosed(1, 5) .reduce(1, (a, b) -> a * b); System.out.println(product); // 출력: 120 (1 * 2 * 3 * 4 * 5)
Share article

silver