Post

[Programmers] 181926번 - 수 조작하기 1 [Java][C++]

[Programmers] 181926번 - 수 조작하기 1 [Java][C++]

문제 링크


1. 아이디어

control 문자열을 앞에서부터 순서대로 읽으며 w, s, d, a에 대응하는 +1, -1, +10, -10n에 그대로 누적해줬다.


2. 복잡도

시간복잡도공간복잡도
$O(N)$$O(1)$

$N$ = control 길이


3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public int solution(int n, String control) {
        for (char c : control.toCharArray()) {
            if (c == 'w') {
                n += 1;
            } else if (c == 's') {
                n -= 1;
            } else if (c == 'd') {
                n += 10;
            } else {
                n -= 10;
            }
        }

        return n;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>

using namespace std;

int solution(int n, string control) {
    for (char c : control) {
        if (c == 'w') {
            n += 1;
        } else if (c == 's') {
            n -= 1;
        } else if (c == 'd') {
            n += 10;
        } else {
            n -= 10;
        }
    }

    return n;
}

This post is licensed under CC BY 4.0 by the author.