[Programmers] #181879 - 길이에 따른 연산 [Java][C++][Python]
[Programmers] #181879 - 길이에 따른 연산 [Java][C++][Python]
1. 아이디어
num_list의 길이가 11 이상이면 전체 원소의 합을, 10 이하이면 전체 원소의 곱을 계산해 반환하면 된다. 원소를 모두 곱해도 32비트 정수 범위(2,147,483,647)를 넘지 않음이 보장되므로 오버플로우는 고려하지 않아도 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = num_list의 길이)
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[] 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.