프로그래머스/0단계
이어 붙인 수
긴가우딘
2025. 1. 9. 00:39
문제 설명
정수가 담긴 리스트 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;
}
}