ailen22 2024. 1. 26. 00:53

[문제]

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

 

num_list result
[3, 4, 5, 2, 1] 393
[5, 7, 8, 3] 581

 

 

 

 

[답]

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 == 1) {
                 odd += (num_list[i];
             } else {
                 even += num_list[i];
             }
         }
        answer = Integer.parseInt(odd) + Integer.parseInt(even);
        return answer;
    }
}

 

 

 

 

[다른사람 풀이]

class Solution {
    public int solution(int[] num_list) {
        int answer = 0;

        int even = 0;
        int odd = 0;

        for(int num : num_list) {
            if(num % 2 == 0) {
                even *= 10;
                even += num;
            } else {
                odd *= 10;
                odd += num;
            }
        }
        answer = even + odd;
		return answer;
    }
}