[Programmers] #181882 - 조건에 맞게 수열 변환하기 1 [Java][C++][Python]
[Programmers] #181882 - 조건에 맞게 수열 변환하기 1 [Java][C++][Python]
1. 아이디어
50 이상의 짝수는 2로 나누고, 50 미만의 홀수는 2를 곱하고, 나머지는 그대로 두는 변환을 원소마다 적용하면 된다. 두 조건은 50 이상인지와 50 미만인지로 갈려 겹치지 않으므로 한 원소에 변환이 한 번만 적용된다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] solution(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= 50 && arr[i] % 2 == 0) {
arr[i] /= 2;
} else if (arr[i] < 50 && arr[i] % 2 != 0) {
arr[i] *= 2;
}
}
return arr;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> arr) {
for (int& x : arr) {
if (x >= 50 && x % 2 == 0) {
x /= 2;
} else if (x < 50 && x % 2) {
x *= 2;
}
}
return arr;
}
int&로 받아 원소를 제자리에서 바꿨다.
1
2
3
4
5
6
7
8
9
10
def transform(x):
if x >= 50 and x % 2 == 0:
return x // 2
if x < 50 and x % 2:
return x * 2
return x
def solution(arr):
return [transform(x) for x in arr]
This post is licensed under CC BY 4.0 by the author.