div1 + 2 c

Problem - C - Codeforces

#include 
//using int_max = 0x3f3f3f3f;
#define long_max 9223372036854775807;
using namespace std;
typedef long long ll;
typedef pair PII;
typedef pair PDD;
using VI = vector;
typedef unsigned long long ull;
const int MAXN = 1e6;

int bit(int x,int pos){
    return (x >> pos) & 1;
}


void solve(){
    int x;
    cin>>x;
    VI a;
    a.push_back(x);
    int p ;
    for(int i=0;;i++){
        if(bit(x,i)) {
            if (x == (1 << i)) {
                p = i;
                break;
            }
            x -= (1 << i);
            a.push_back(x);
        }
    }
    while(p){
        x /= 2;
        a.push_back(x);
        p--;
    }
    cout<>t;
    while (t--){
        solve();
    }

}

如何把一个数变成2的n次幂

从最低位开始枚举,如果第 i 位为 1 ,若x == (1 << i )就为2^i ,否则就减去(1<< i)

然后每次减去一半 2^k - 2^(k-1) = 2^(k-1)

你可能感兴趣的:(思维构造,算法,c++,数据结构)