[프로그래머스 / Java] 피자 나눠 먹기 (2)
- Coding Test / 프로그래머스
- 2023. 9. 28.
문제 출처 : 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의 최소 공배수를 찾는 것을 알 수 있음.
'Coding Test > 프로그래머스' 카테고리의 다른 글
[프로그래머스 / Java] 분수의 덧셈 (0) | 2023.09.21 |
---|---|
[프로그래머스 / Python] 약수의 합 (0) | 2021.07.01 |
[프로그래머스 / Python] 시저 암호 (0) | 2021.07.01 |
[프로그래머스 / Python] 소수 찾기 (0) | 2021.06.22 |
[프로그래머스 / Python] 서울에서 김서방 찾기도움말 (0) | 2021.06.22 |