본문 바로가기

CodingTest/Programmers81

[프로그래머스] Lv.0 가까운 수 class Solution { public int solution(int[] array, int n) { int answer = 99; int num = 100; for(int i=0; i < array.length; i++){ if(Math.abs(n-array[i]) < answer){ answer = Math.abs(n-array[i]); //answer값 새로 갱신 num = array[i]; }else if(Math.abs(n-array[i])==answer && array[i] < num){ num = array[i]; //혹시 가까운 차이는 같은데 array[i]가 더 작을 경우 } //ex) n=11인데 10과 12를 비교하는 경우 } return num; } } answer는 n과 배열의.. 2022. 12. 15.
[프로그래머스] LV.0 k의 개수 class Solution { public int solution(int i, int j, int k) { int answer = 0; for(int s=i; s0){ if(num%10==k) answer++; num/=10; } } return answer; } } i부터 j까지의 숫자 중 k가 있으면 카운트1 증가시켜주는 문제이므로 for문의 범위를 i 부터 j까지 하고 i부터 시작하기 때문에 s=i 초기화 후 s를 로직에 그대로 사용하면 잘못된 풀이다. 왜냐하면 밑에 while에서 해당 숫자를 %하고 다시 /해서 사용하는데 s를 그대로 사용하면 for문의 조건식에 큰 영향을 미치기 때문이다. 따로 num이라는 변수에 그때그때 s를 담아서 사용해주면 해결할 수 있다. 2022. 12. 15.
[프로그래머스] Lv.0 2차원으로 만들기* class Solution { public int[][] solution(int[] num_list, int n) { int[][] answer =new int[num_list.length/n][n]; int idx = 0; for(int i=0; i 2022. 12. 15.
[프로그래머스] Lv.0 팩토리얼 class Solution { public int solution(int n) { int i=1; int mul=1; while(true) { mul *= i; if(mul==n) break; else if(mul>n) { i--; break; } i++; } return i; } } 팩토리얼은 a! = a*a-1*a-2*....3*2*1 이다. 여기서 팩토리얼 한게 n이거나 n보다 작거나 큰 수가 나왔을 때는 작은 것을 출력해줘야 하므로 mul==n일 때와 mul>n 일 때 i를 하나 빼서 출력시켜줬다. 2022. 12. 1.
[프로그래머스] Lv.0 A로 B 만들기 class Solution { public int solution(String before, String after) { for(int i=0; i 2022. 12. 1.
[프로그래머스] Lv.0 모스부호 class Solution { public String solution(String letter) { String answer = ""; String []arrStr = letter.split(" "); String []mose = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; for(int i=0; i 2022. 12. 1.
[프로그래머스] Lv.0 중복된 문자 제거** class Solution { public String solution(String my_string) { StringBuilder answer = new StringBuilder(); while(true) { if(my_string.equals("")) { break; }else { answer.append(my_string.charAt(0)); my_string = my_string.replaceAll(Character.toString(my_string.charAt(0)), ""); } } return answer.toString(); } } 필자는 문자열 문제만 나오면 우선 부담이 된다. 자르고 탐색하고 정렬하고 형변환하는 등 문제의 종류가 너무나 다양한데 다양한 메서드를 알아야 좀 더 문제를 쉽게.. 2022. 11. 30.
[프로그래머스] Lv.0 합성수 찾기 class Solution { public int solution(int n) { int answer = 0; boolean array[] = new boolean[n+1]; // 소수가 아니면 true로 바꾸기 // 1은 소수가 아니므로 true array[1] = true; //에라토스테네스의 체로 구하기 for(int i=2; i 2022. 11. 30.
[프로그래머스] Lv.0 369게임 class Solution { public int solution(int order) { int answer = 0; while(order>0){ if(order%10!=0 && (order%10)%3==0) answer++; order/=10; } return answer; } } 뒤에서 하나씩 비교해서 3의 배수인지 판별한 후 맞으면 1씩 증가 시켰다. 그런데 처음에 조건문에서 (order%10)%3==0 일 때만 증가시켰더니 테스트케이스에서 실패가 나와서 원인을 찾아보니 10이나 100과 같이 0이 나오면 0%3했을 때 0이 나와서 값을 증가시켜서 실패가 나왔다. 그래서 추가로 order%10!=0 && (order%10)%3==0 조건을 넣어서 풀이했다. 2022. 11. 30.
728x90
반응형