programmers Day25

Hwani·2024년 5월 31일

프로그래머스 DAY 1~25

목록 보기
25/51

문제 - 문자열 밀기

풀이

class Solution {
    public int solution(String A, String B) {
        if (A.equals(B)) {
            return 0;
        }

        // 문자열 길이를 확인
        int length = A.length();

        // A를 한 칸씩 밀면서 B와 비교
        for (int i = 1; i < length; i++) {
            A = A.charAt(length - 1) + A.substring(0, length - 1);  // 문자열을 오른쪽으로 한 칸 밀기
            if (A.equals(B)) {
                return i;
            }
        }

        // 모든 경우를 다 확인했는데도 B와 일치하지 않으면 -1을 반환
        return -1;
    }
}

설명

문제 - 종이 자르기

풀이

class Solution {
    public int solution(int M, int N) {
        return M * N - 1;
    }
}

설명

문제 - 연속된 수의 합

풀이

class Solution {
    public int[] solution(int num, int total) {
        int[] answer = new int[num];

        int x = (2 * total / num - (num - 1)) / 2;

        for (int i = 0; i < num; i++) {
            answer[i] = x + i;
        }

        return answer;
    }
}

설명

문제 - 다음에 올 숫자

풀이

class Solution {
    public int solution(int[] common) {
        int answer = 0;

        int x = common[1] - common[0];
        int y = common[2] - common[1];

        if (x == y) {
            answer = common[common.length - 1] + y; // 등차수열일 경우
        } else {
            answer = common[common.length - 1] * common[2] / common[1]; // 등비수열일 경우
        }

        return answer;
    }
}

설명

profile
개발자될거야

0개의 댓글