C++:: 프로그래머스 < 키패드 누르기 >

jahlee·2023년 7월 13일
0

프로그래머스_Lv.1

목록 보기
40/75
post-thumbnail

중간 키패드일때 주의해야하는 문제이다. 크게 어렵지는 않지만 생각보다 까다로울 수 있다.

#include <string>
#include <vector>
using namespace std;

string solution(vector<int> numbers, string hand) {
    string answer = "";
    int pos_left=10, pos_right=12;
    for (auto num : numbers) {
        if (num == 0) num = 11;
        bool left = true;
        
        if (num % 3 == 0) {
            left = false;
        } else if (num % 3 == 2) {
            int dist_left = 0, dist_right = 0;
            if (pos_left % 3 == 1) dist_left++;
            if (pos_right % 3 == 0) dist_right++;
            
            if (dist_left) dist_left += abs((pos_left+1-num)/3);
            else dist_left += abs((pos_left-num)/3);
            
            if (dist_right) dist_right += abs((pos_right-1-num)/3);
            else dist_right += abs((pos_right-num)/3);
            
            
            if (dist_left > dist_right || (dist_left == dist_right && hand == "right"))
                left = false;
        }
        if (left) {
            pos_left = num;
            answer += 'L';
        } else {
            pos_right = num;
            answer += 'R';
        }
    }
    return answer;
}

0개의 댓글