알고리즘
[Java] 프로그래머스 없는 숫자 더하기
개발자 박현준
2023. 2. 8. 17:03
728x90
문제 설명
0부터 9까지의 숫자 중 일부가 들어있는 정수 배열 numbers가 매개변수로 주어집니다. numbers에서 찾을 수 없는 0부터 9까지의 숫자를 모두 찾아 더한 수를 return 하도록 solution 함수를 완성해주세요.
제한사항
- 1 ≤ numbers의 길이 ≤ 9
- 0 ≤ numbers의 모든 원소 ≤ 9
- numbers의 모든 원소는 서로 다릅니다.
입출력 예
입출력 예 설명
입출력 예 #1
- 5, 9가 numbers에 없으므로, 5 + 9 = 14를 return 해야 합니다.
입출력 예 #2
- 1, 2, 3이 numbers에 없으므로, 1 + 2 + 3 = 6을 return 해야 합니다.
코드 설명
import java.util.Scanner;
public class Solution {
public int solution(int[] numbers) {
// 방법1
// int answer = 0;
// String numbersStr = "";
// for (int i = 0; i < numbers.length; i++) {
// numbersStr += numbers[i]; // numbers를 String으로 저장
// }
//
// for (int j = 0; j <= 9; j++) {
// if (numbersStr.contains(String.valueOf(j)) == false) { // numbersStr에 j를 문자로 바꾼 값이 없으면
// answer += j; // answer += j를 해준다.
// }
// }
// 방법2
int answer = 45; // 0 ~ 9 까지 더한 값 1 2 3 4 5 6 7 8 9
for (int x : numbers) { // x에 numbers를 넣어주면서 있는 값들을 answer -= x 해줌.
answer -= x;
}
return answer;
}
public static void main(String[] args) {
Solution T = new Solution();
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] numbers = new int[num];
for (int i = 0; i < num; i++) {
numbers[i] = sc.nextInt();
}
System.out.println(T.solution(numbers));
sc.close();
}
}
728x90