Post

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

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

문제 링크


1. 아이디어

control을 앞에서부터 한 글자씩 읽으며 $n$에 곧바로 반영하면 된다.


2. 코드

풀이 [Java][C++][Python]

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++;
            } else if (c == 's') {
                n--;
            } 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
#include <bits/stdc++.h>
using namespace std;

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

    return n;
}
1
2
3
4
5
6
7
8
9
10
11
12
def solution(n, control):
    for c in control:
        if c == "w":
            n += 1
        elif c == "s":
            n -= 1
        elif c == "d":
            n += 10
        else:
            n -= 10

    return n

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