Algorithm

Hackerrank - Jumping on the Clouds: Revisited, Find Digits, Extra Long Factorials

HI2 2021. 2. 5. 20:45

[풀이 - Jumping on the Clouds: Revisited]

더보기
int jumpingOnClouds(vector<int> c, int k) 
{
    int result = 100;
    int length = c.size();
    int idx = 0;
    //
    while(true)
    {
        idx = (idx + k) % length;
        //
        if(c[idx] == 1)
            result -= 3;
        else
            result -= 1;
        //
        if(idx == 0 || result <= 0)
            break;
    }
    //
    return result;
}

 

[풀이 - Find Digits]

더보기
int findDigits(int n)
{
    int result = 0;
    //
    int num = n;
    int d = 0;
    //
    while(num > 0)
    {
        d = num % 10;
        //
        if((d != 0) && (n % d == 0))
            ++result;
        //
        num /= 10;
    }
    //
    return result;
}

 

[풀이 - Extra Long Factorials]

더보기
typedef long long ll;
//
#define pb push_back
//
const int base = 1e9;
//
typedef vector<int> BigInt;

void Set(BigInt &a)
{
    while (a.size() > 1 && a.back() == 0)
        a.pop_back();
}

void Print(BigInt a)
{
    Set(a);
    //
    if(a.size() == 0)
        cout << 0;
    else
        cout << a.back();
    //
    for (int i = a.size()-2; i >= 0; --i)
        printf("%09d", a[i]);
    //
    cout << endl;
}

BigInt Integer(string s)
{
    BigInt ans;
    //
    if (s[0] == '-')
        return ans;
    //
    if (s.size() == 0)
    {
        ans.pb(0);
        return ans;
    }
    //
    while (s.size() % 9 != 0)
        s = '0' + s;
    //
    for (int i = 0; i < s.size(); i += 9)
    {
        int v = 0;
        //
        for (int j = i; j < i + 9; j++)
            v = v * 10 + (s[j] - '0');
        //
        ans.insert(ans.begin(), v);
    }
    Set(ans);
    //
    return ans;
}

BigInt operator * (BigInt a, BigInt b)
{
    Set(a);
    Set(b);
    //
    BigInt ans;
    //
    ans.assign(a.size() + b.size(), 0);
    //
    for(int i = 0; i < a.size(); ++i)
    {
        ll carry = 0ll;
        for (int j = 0; j < b.size() || carry > 0; j++)
        {
            ll s = ans[i+j]
                + carry
                + (ll)a[i] * (j < b.size() ? (ll)b[j] : 0ll);
            ans[i + j] = s % base;
            carry = s / base;
        }
    }
    //
    Set(ans);
    //
    return ans;
}

void extraLongFactorials(int n)
{
    BigInt a = Integer("1");
    //
    for(int i = 1 ; i <= n ; ++i)
    {
        BigInt b = Integer(to_string(i));
        a = a * b;
    }
    //
    Print(a);
}

# 참고 : codeforces.com/blog/entry/16380