[Programmers] #181879 - 길이에 따른 연산 [Java][C++][Python]
[Programmers] #181879 - 길이에 따른 연산 [Java][C++][Python]
1. 아이디어
리스트 길이가 11 이상이면 모든 원소의 합을, 10 이하이면 모든 원소의 곱을 반환하는 분기를 그대로 구현하면 된다. 곱이 2,147,483,647을 넘는 입력은 주어지지 않아 32비트 정수로 충분하다.
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[] num_list) {
if (num_list.length >= 11) {
int sum = 0;
for (int x : num_list) {
sum += x;
}
return sum;
} else {
int mul = 1;
for (int x : num_list) {
mul *= x;
}
return mul;
}
}
}
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(vector<int> num_list) {
if (num_list.size() >= 11) {
int sum = 0;
for (int x : num_list) {
sum += x;
}
return sum;
} else {
int mul = 1;
for (int x : num_list) {
mul *= x;
}
return mul;
}
}
1
2
3
4
5
6
7
8
import math
def solution(num_list):
if len(num_list) >= 11:
return sum(num_list)
else:
return math.prod(num_list)
This post is licensed under CC BY 4.0 by the author.