[Programmers] #181926 - 수 조작하기 1 [Java][C++][Python]
제어 문자열의 문자에 따라 정수를 1 또는 10씩 증감시키는 워밍업 문제.
[Programmers] #181926 - 수 조작하기 1 [Java][C++][Python]
1. 아이디어
정수 n과 제어 문자열 control이 주어질 때, control을 앞에서부터 순회하며 문자에 따라 n을 조작하면 되는 문제다. w는 1 증가, s는 1 감소, d는 10 증가, a는 10 감소를 의미하므로, 각 문자를 확인하며 그에 대응하는 값을 더하거나 빼면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = control의 길이)
3. 코드
풀이 [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.