문제
내가 작성한 오답
: int로 계산했기 때문에 나눗셈을 하면 오류가 발생
class Solution {
public int solution(int[][] dots) {
if(isParallel(dots[0],dots[1],dots[2],dots[3])) return 1;
if(isParallel(dots[0],dots[2],dots[1],dots[3])) return 1;
if(isParallel(dots[0],dots[3],dots[1],dots[2])) return 1;
return 0;
}
private boolean isParallel(int[] d1, int[] d2, int[] d3, int[] d4 ){
return (d1[0]-d2[0])/(d1[1]-d2[1]) == (d3[0]-d4[0])/(d3[1]-d4[1]);
}
}
내가 작성한 정답
: 곱셈으로 변경
class Solution {
public int solution(int[][] dots) {
if(isParallel(dots[0],dots[1],dots[2],dots[3])) return 1;
if(isParallel(dots[0],dots[2],dots[1],dots[3])) return 1;
if(isParallel(dots[0],dots[3],dots[1],dots[2])) return 1;
return 0;
}
private boolean isParallel(int[] d1, int[] d2, int[] d3, int[] d4 ){
return (d1[0]-d2[0])*(d3[1]-d4[1]) == (d3[0]-d4[0])*(d1[1]-d2[1]);
}
}
다른 사람들의 정답
class Solution {
int[][] dots;
public int solution(int[][] dots) {
// dots 배열을 인스턴스 변수로 저장
// -> 다른 메서드(parallel)에서도 쉽게 접근 가능
this.dots = dots;
if (parallel(0, 1, 2, 3)) return 1;
if (parallel(0, 2, 1, 3)) return 1;
if (parallel(0, 3, 1, 2)) return 1;
return 0;
}
boolean parallel(int a, int b, int c, int d) {
int x = (dots[a][0] - dots[b][0]) * (dots[c][1] - dots[d][1]);
int y = (dots[a][1] - dots[b][1]) * (dots[c][0] - dots[d][0]);
return x == y || x == -y;
}
}
Share article