본문 바로가기
(문제풀이)

프로그래머스(JAVA) : 자릿수 더하기

by cogito-new 2022. 9. 11.

Stream 사용한 풀이

import java.util.*;


public class Solution {
    public int solution(int n) {
        String number = String.valueOf(n);
        // int 인 경우, 각 자리 분리가 안되서 String 변환 후, Stream 처리
        List<String> answerList = Arrays.asList(number.split(""));

        int answer = answerList.stream()
                .map(Integer::parseInt)
                .reduce((x,y) -> x+y)
                .get();
        return answer;
    }
}

기존 풀이

import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;
        int a = 0;
		String N1;
		N1 = n + "";
		String[] N2 = N1.split("");
		for(int i = 0; i<N1.length(); i++) {
			answer +=Integer.parseInt(N2[i]);
		}
        return answer;
    }
}

 

반응형