数的乘积

发布时间 2023-04-11 22:10:51作者: wscqwq

数的乘积

考虑用除法解决这个问题。因为如果这些数的乘积超过了 \(10^{18}\),那么用 \(10^{18}\) 依次除以这些数肯定存在一个时刻变为 \(0\)。所以就可以在不使用 __int128 这类黑科技的情况下方便的判断。注意如果有一个数是 \(0\) 应该立刻停下输出 \(0\),不然可能出现 Float Point Exception

#include<bits/stdc++.h>
using namespace std;
#define L(i,l,r) for(int i=l;i<=r;++i)
#define R(i,l,r) for(int i=r;i>=l;--i)
typedef long long ll;
ll a=1e18,b=1;
bool flag;
int main(){
    // freopen("1.in","r",stdin);
    // freopen("1.out","w",stdout);
    // ios::sync_with_stdio(0);
    // cin.tie(0);
    // cout.tie(0);
    int n;
    scanf("%d",&n);
    while(n--){
        ll x;
        scanf("%lld",&x);
        if(!x)return puts("0"),0;
        a/=x;
        if(!a)flag=1;
        b*=x;
    }
    printf("%lld",flag?-1:b);
    return 0;
}