2020.3.18 Luogu1010 幂次方

递归+二进制
注意判断1

代码:

#include <iostream>
#include <cstdio>

using namespace std;

int n;

inline string div(int x)
{
    if (x == 0)
        return "0";
    if (x == 1)
        return "2(0)";
    if (x == 2)
        return "2";
    int p[20], q = x, id = 0;
    while (q != 1)
    {
        p[id++] = q % 2;
        q /= 2;
    }
    p[id++] = 1;
    string ret;
    if (id - 1 == 1)
        ret = "2";
    else
        ret = "2(" + div(id - 1) + ")";
    for (int i = id - 2; i >= 0; --i)
    {
        if (p[i] == 1 && i != 1)
            ret += "+2(" + div(i) + ")";
        if (p[i] == 1 && i == 1)
            ret += "+2";
    }
    return ret; 
}

int main()
{
    cin >> n;
    cout << div(n) << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/pipa-peng/p/12520833.html
今日推荐