강의로 돌아가기
최동환

스포(자바) 나머지와 몫연산을 통한 거리계산

나머지와 몫연산을 위해 계산시 키패드에서 1을 뺍니다.

0 1 2
3 4 5
6 7 8
 10

작성중인 코드―Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
       public String solution(int[] numbers, String hand) {
        int l = 9, r = 11; // 시작시 왼쪽엄지는 * 키패드(숫자로 10) , 오른쪽 엄지는 # 키패드(숫자로 12)
        char result;
        StringBuffer sb = new StringBuffer();
        for (int n : numbers) {
            n--;
            if (n % 3 == 0) { // 1,4,7 일때
                l = n;
                result = 'L';
            } else if (n % 3 == 2) { // 3,6,9 일때
                r = n;
                result = 'R';
            } else { // 2,5,8,0 일때
                int ld = getDistance(l, n);
                int rd = getDistance(r, n);

                if (ld < rd) {
                    l = n;
                    result = 'L';
                } else if (ld > rd) {
                    r = n;
                    result = 'R';
                } else if (hand.equals("right")) {
                    r = n;
                    result = 'R';
                } else {
                    l = n;
                    result = 'L';
                }
            }
            sb.append(result);
        }

        return sb.toString();
    }
    public int getDistance(int from, int to){
        // 0 은 키패드 11로 취급
        if(from < 0) from = 10;
        if(to < 0) to = 10;
        // 나머지의 차 -> 좌우 이동횟수, 몫의 차 -> 상하 이동횟수
        return Math.abs(from%3 - to%3) + Math.abs(from/3-to/3);
    }
}
0 개의 답변
답변 쓰기
이 입력폼은 마크다운 문법을 지원합니다.