Post

[Programmers] #181929 - 원소들의 곱과 합 [Java][C++][Python]

[Programmers] #181929 - 원소들의 곱과 합 [Java][C++][Python]

문제 링크


1. 아이디어

모든 원소의 곱과 합의 제곱을 각각 구해 곱이 더 작은지 비교한다.


2. 코드

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

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int solution(int[] num_list) {
        long mul = 1, sum = 0;
        for (int x : num_list) {
            mul *= x;
            sum += x;
        }

        return mul < sum * sum ? 1 : 0;
    }
}

곱이 최대 $9^{10}$이라 int 범위를 넘으므로 long을 썼다.

1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;

int solution(vector<int> num_list) {
    long long mul = 1, sum = 0;
    for (int x : num_list) {
        mul *= x;
        sum += x;
    }

    return mul < sum * sum;
}

곱이 최대 $9^{10}$이라 int 범위를 넘으므로 long long을 썼다.

1
2
3
4
5
import math


def solution(num_list):
    return int(math.prod(num_list) < sum(num_list) ** 2)

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