位运算实现n的所有子集

位运算计算出每一个当前2n(n的范围是0道2n-1)然后加上字符'0'就可以

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    cin >> n;
    for(int i = 0; i < (1 << n); i ++ )
    {
        string s = "";
        for(int j = 0; j < n; j ++ )
        {
            s += ((i >> j) & 1 ) + '0';
        }
        cout << s << endl;
    }
    return 0;
}
posted @ 2021-04-15 21:01  梨花满地  阅读(53)  评论(0)    收藏  举报