[프로그래머스 / Java] 피자 나눠 먹기 (2)

문제 출처 : https://school.programmers.co.kr/learn/courses/30/lessons/120815

문제 풀이

1. remainder 활용 (내 풀이)

class Solution {
    public int solution(int n) {
        int totalPiece = 6;       
        int remainder = totalPiece % n;        
        
        if (remainder == 0) {
            return totalPiece / 6;
        } else {
            while (remainder != 0) {
                totalPiece += 6;
                remainder = totalPiece % n;
            }    
        }
                        
        return totalPiece / 6;
    }
}
  • 먹은 조각이 먹은 사람으로 나누어 떨어져야 하므로 피자 한판 조각만큼 더하면서 나누어떨어질때까지의 먹은 총 조각 갯수를 구함

2. remainder 활용 (다른사람 풀이)

class Solution {
    public int solution(int n) {
        int answer = 0;
        int remainder = n;

        while (remainder != 0) {
            remainder += 6;
            remainder %= n;
            answer++;
        }
        return answer;
    }
}
  • remainder 자체를 먹은사람 수로 생각한 아이디어로 훨씬 깔끔하다.

3. 유클리드 호제법 활용

class Solution {
    private int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    public int lcm(int a, int b) {
        return a * b / gcd(a, b);
    }

    public int solution(int n) {
        return lcm(n, 6) / 6;
    }
}
  • 문제를 잘 분석하면 n 과 6의 최소 공배수를 찾는 것을 알 수 있음.

댓글

Designed by JB FACTORY