Codeforces #596 div1 A/div2 C – p-binary

题目链接:https://codeforces.com/contest/1246/problem/A

题意:给你一个数n和一个数p,问你能否将n拆为一些(2^x+p)形式的部分,x可以为非负整数。如果可以,输出最小答案,否则输出-1。

做法:暴力。因为n不大于int范围,遍历32次即可得到答案,具体实现见代码。

参考代码:

#include <iostream>

using namespace std;
int n, p;

int main()
{
    cin >> n >> p;
    for (int i = 0; i <= 32; i++)
        if (__builtin_popcount(n - i * p) <= i && n - i * p >= i)
        {
            cout << i << endl;
            return 0;
        }
    cout << "-1" << endl;
    return 0;
}
posted @ 2019-11-01 14:34  mapleaves  阅读(106)  评论(0)    收藏  举报