[algorithm] 이어 붙인 수

인철·2024년 2월 25일
0

algorithm

목록 보기
65/91
post-thumbnail

정수가 담긴 리스트 num_list가 주어집니다. num_list의 홀수만 순서대로 이어 붙인 수와 짝수만 순서대로 이어 붙인 수의 합을 return하도록 solution 함수를 완성해주세요.

class Solution{
	public int solution(int[] num_list){
    	int answer = 0;
        String odd = "":
        String even = "";
        
        for (int i = 0; i < num_list.length; i++){
        	if(num_list[i]  % 2 == 0){
            	even  = even + Integer.toString(num_list[i]);
                // even = Integer.toString(num_list[i]); 이렇게 할 시 매번 반복이 될 때마다
                // 갱신이 되기 때문에 even 기존에 있던 수를 같이 더해야 한다.
            } else {
            	odd = odd + Integer.toString(num_list[i]);
            }
        }
        answer = Integer.parseInt(even) + Integer.parseInt(odd);
        // 문자열을 다시 정수로 반환을 한다.
        return answer;
    }
}

// 문자열로 치환하는 이유  : 단순히 숫자를 더하는게 아니라 이어 붙이는 과정을 거쳐야 하기 때문
profile
같은글이있어도양해부탁드려요(킁킁)

0개의 댓글