문제 설명
정수가 담긴 리스트 num_list가 주어집니다. num_list의 홀수만 순서대로 이어 붙인 수와 짝수만 순서대로 이어 붙인 수의 합을 return하도록 solution 함수를 완성해주세요.
문제 읽으면서 정리
- num_list의 홀수만/짝수만 순서대로 이어붙인 수의 합
- num_list가 3,4,5,2,1이라고 할 때 - 홀수: 351, 짝수:42, 홀수 + 짝수: 351 + 42 = 393
for(int i = 1; i<num_list.length; i++) {
if(num_list[i] % 2 ==1) {
odd += num_list[i];
}
else even += num_list[i];
answer = odd + even;
}
문제 풀면서 고친 부분
- odd와 even이 이어 붙인 수가 되려면 string 타입이 되어야 함
- string을 정수형으로 바꾸는 과정에서 string이 빈 문자열일 경우 Intrger.parseInt() 불가: NumberFormatException에러 발생 > odd와 even을 "0"으로 초기화 (odd와 even 안에 정수만 있기 때문에 가능)
class Solution {
public int solution(int[] num_list) {
int answer = 0;
String odd = "0";
String even = "0";
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;
}
}
'프로그래머스 > 0단계' 카테고리의 다른 글
수 조작하기 1 (0) | 2025.01.12 |
---|---|
마지막 두 원소 (0) | 2025.01.12 |
코드 처리하기 (0) | 2025.01.09 |
[PCCE 기출문제] 8번 / 닉네임 규칙 (0) | 2025.01.06 |
[PCCE 기출문제] 7번 / 버스 (1) | 2025.01.06 |