프로그래머스LV1_1

개발자를 꿈꾸는 뚱이·2026년 3월 11일

코딩테스트 스터디

목록 보기
18/39

LV0를 어느정도 풀었다고 판단해서 LV1로 넘어갔으며 풀다가 많이 막힌다 싶으면 LV0에서 문법과 기초 구현을 좀 더 연습해봐야겠다.

LV1 기록 규칙

  • 막히거나 어려웠던 문제가 생긴다면 상세히 기록하고 그게 아니라면 한 줄 코멘트 느낌 진행

기록

  • 짝수와 홀수
    class Solution {
        public String solution(int num) {
            String answer = (num % 2 == 0)? "Even" : "Odd";
            return answer;
        }
    }
  • 평균 구하기
    class Solution {
        public double solution(int[] arr) {
            double answer = 0;
            for(int num : arr) answer += (double)num;
            return answer / arr.length;
        }
    }
  • x만큼 간격이 있는 n개의 숫자
    class Solution {
        public long[] solution(int x, int n) {
            long[] answer = new long[n];
            for(int i = 0; i < n; i++){
                answer[i] = (long)x + (long)x * i;
            }
            return answer;
        }
    }
제한 사항에서 -10000000 ≤ x ≤ 10000000 이고 n은 1000 이하의 자연수라서 약 -21억 ~ 21억인 int 범위가 넘어갈 수 있어 계산할 때 long자료형을 하여야 통과가 됨
  • 나머지가 1인 되는 수 찾기
    class Solution {
        public int solution(int n) {
            int answer = 0;
            for(int i = 2; i < n; i++){
                if(n % i == 1){
                    answer = i;
                    break;
                }
            }
            return answer;
        }
    }
  • 문자열을 정수로 바꾸기
    class Solution {
        public int solution(String s) {
            int answer = Integer.parseInt(s);
            return answer;
        }
    }
  • 약수의 합
    class Solution {
        public int solution(int n) {
            int answer = 0;
            for(int i = 1; i <= n; i++){
                if(n % i == 0) answer += i;
            }
            return answer;
        }
    }
  • 정수 내림차순으로 배치하기
    ;import java.util.*;
    
    class Solution {
        public long solution(long n) {
            long answer = 0;
            String s = n + "";
            int[] num = new int[s.length()];
            for(int i = 0; i < s.length(); i++){
                char c = s.charAt(i);
                num[i] = c - '0';
            }
            Arrays.sort(num);
            String ans = "";
            for(int i = num.length - 1; i >= 0; i--) ans += (char)(num[i] + '0');
            answer = Long.parseLong(ans);
            return answer;
        }
    }
    
    // 개선
    import java.util.*;
    
    class Solution {
        public long solution(long n) {
            char[] chars = String.valueOf(n).toCharArray();
            Arrays.sort(chars);
            StringBuilder sb = new StringBuilder()
            for (int i = chars.length - 1; i >= 0; i--) {
                sb.append(chars[i]); 
            }
            return Long.parseLong(sb.toString());
        }
    }
정수는 문자열로 바꾸어 처리하는 방식을 택했는데 자바의 함수를 활용하면 좀 더 빠르게 처리 가능하므로 파악해두자!
  • 하샤드 수
    class Solution {
        public boolean solution(int x) {
            int X = x;
            int sum = 0;
            while(X > 0){
                sum += X % 10;
                X /= 10;
            }
            return x % sum == 0;
        }
    }
각 자리수의 합을 계산하여 구하고 나누어 떨어지는지 여부를 반환하면 해결
  • 정수 제곱근 판별
    class Solution {
        public long solution(long n) {
            long answer = -1;
            double sqrt = Math.sqrt(n);
            if(sqrt % 1 == 0) answer = ((long)sqrt + 1) * ((long)sqrt + 1);
            return answer;
        }
    }
  • 자연수 뒤집어 배열로 만들기
    class Solution {
        public int[] solution(long n) {
            int length = Long.toString(n).length();
            int[] answer = new int[length];
            int idx = 0;
            while(n > 0){
                answer[idx++] = (int)(n % 10);
                n /= 10;
            }
            return answer;
        }
    }
수의 길이만큼 배열을 만들어 10으로 나눈 나머지를 넣고 나누는 식으로 배열에 넣으면 해결
  • 자릿수 더하기
    import java.util.*;
    
    public class Solution {
        public int solution(int n) {
            int answer = 0;
            while(n > 0){
                answer += n % 10;
                n /= 10;
            }
            return answer;
        }
    }
  • 두 정수 사이의 합
    class Solution {
        public long solution(int a, int b) {
            if(a == b) return a;
            long answer = 0;
            if(a < b)
                for(int i = a; i <= b; i++) answer += i;
            else
                for(int i = b; i <= a; i++) answer += i;
            return answer;
        }
    }
    
    // 등차수열 합
    class Solution {
        public long solution(int a, int b) {
            long min = Math.min(a, b);
            long max = Math.max(a, b);
            return (max - min + 1) * (min + max) / 2;
        }
    }
반복문으로 풀었는데 등차수열 합 공식을 활용하면 더 빠르게 해결할 수 있다.
공식 : (두 수 사이의 총 숫자 개수)×(양끝 숫자의 합)2\frac{(\text{두 수 사이의 총 숫자 개수}) \times (\text{양끝 숫자의 합})}{2}
  • 문자열 내 p와 y의 개수
    class Solution {
        boolean solution(String s) {
            int p = 0, y = 0;
            for(char c : s.toCharArray()){
                if(c == 'p' || c == 'P') p += 1;
                else if(c == 'y' || c == 'Y') y += 1;
            }
            return p == y;
        }
    }
전체를 순회하면서 p와 y의 수를 비교하면 해결
  • 음양 더하기
    class Solution {
        public int solution(int[] absolutes, boolean[] signs) {
            int answer = 0;
            for(int i = 0; i < absolutes.length; i++){
                if(signs[i]) answer += absolutes[i];
                else answer -= absolutes[i];
            }
            return answer;
        }
    }
해당 인덱스가 음인지 양인지 체크해서 answer에 누적하여 해결
  • 없는 숫자 더하기
    class Solution {
        public int solution(int[] numbers) {
            int answer = 0;
            boolean[] check = new boolean[10];
            for(int num : numbers) check[num] = true;
            for(int i = 1; i <= 9; i++){
                answer += (!check[i])? i : 0;         
            }
            return answer;
        }
    }
    
    class Solution {
        public int solution(int[] numbers) {
            int answer = 45;
            for (int num : numbers) {
                answer -= num;
            }
            return answer;
        }
    }
boolean 배열로 나온 숫자를 체크해서 안 나온 숫자를 누적하거나 전체합에서 나온 수를 빼는 방법 2가지 모두 가능
  • 나누어 떨어지는 숫자 배열
    import java.util.*;
    
    class Solution {
        public int[] solution(int[] arr, int divisor) {
            int cnt = 0;
            for(int i = 0; i < arr.length; i++)
                if(arr[i] % divisor == 0) cnt++;
            if(cnt == 0) return new int[]{-1};
            int[] answer = new int[cnt];
            int idx = 0;
            for(int num : arr)
                if(num % divisor == 0) answer[idx++] = num;
            Arrays.sort(answer);
            return answer;
        }
    }
    
    // ArrayList 활용
    import java.util.*;
    
    class Solution {
        public int[] solution(int[] arr, int divisor) {
            ArrayList<Integer> list = new ArrayList<>();
            for(int num : arr) {
                if(num % divisor == 0) {
                    list.add(num);
                }
            }
            if(list.isEmpty()) {
                return new int[] {-1};
            }
            Collections.sort(list);
            int[] answer = new int[list.size()];
            for(int i = 0; i < list.size(); i++) {
                answer[i] = list.get(i);
            }
            
            return answer;
        }
    }
나누어 떨어지는 수의 개수를 세어 해당 개수만큼 배열에 생성해 배열을 만들고 정렬하면 해결/ArrayList를 활용하면 반복문 1번을 안해도 되어 좀 더 빠르고 간단함
  • 서울에서 김서방 찾기
    import java.util.*;
    
    class Solution {
        public String solution(String[] seoul) {
            int idx = Arrays.asList(seoul).indexOf("Kim");
            return "김서방은 " + idx + "에 있다";
        }
    }
  • 콜라츠 추측
    class Solution {
        public int solution(long num) {
            int answer = 0;
            while(num != 1 && answer <= 500){
                num = (num % 2 == 0)? num / 2 : num * 3 + 1;
                answer++;
            }
            return (answer > 500)? -1 : answer;
        }
    }
함수 매개변수 자료형이 int였는데 실패하길래 보니까 int 자료형을 넘어갈 수도 있어서 long로 바꿔야 한다.
  • 핸드폰 번호 가리기
    class Solution {
        public String solution(String phone_number) {
            String answer = "";
            int l = phone_number.length();
            for(int i = 0; i < l - 4; i++) answer += '*';
            for(int i = l - 4; i < l ;i++) answer += phone_number.charAt(i);
            return answer;
        }
    }
    
    //StringBuilder 활용
    class Solution {
        public String solution(String phone_number) {
            String answer = "";
            int l = phone_number.length();
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < l - 4; i++) sb.append("*");
            for(int i = l - 4; i < l ;i++) sb.append(phone_number.charAt(i));
            // answer.append(phone_number.substring(l - 4)); 이것도 가능
            answer = sb.toString();
            return answer;
        }
    }
String 에 +로 더하는 것보다 StringBuilder.append를 활용하는 것이 훨씬 빠르다.(실행 시간을 보면 알 수 있음) StringBuilder를 최대한 활용해보자
  • 가운데 글자 가져오기
    class Solution {
        public String solution(String s) {
            int l = s.length();
            String answer = (l % 2 == 0)? s.substring(l/2-1, l/2 + 1) : s.substring(l/2, l/2 + 1);
            return answer;
        }
    }
길이가 2로 나누어 떨어지는지 여부로 가운데 2글자나 1글자를 반환하여 해결
profile
개발자가 되기 위해 열심히 춤추는 중이에요 🕺

0개의 댓글