我想知道如何递归地编写类似的东西,还是使用不同的循环系统:
std::string a = "00000000";
for (int i = 0; i<8; i++) {
a[i] = '1';
for (int j = 0; j<8; j++) {
if (i!=j) {
a[j] = '1';
... //more for loops with the same structure
std::cout<<a[j]<<"\n";
a[j] = '0';
}
a[i] = '0';
}我试图打印出每一个0和1可能的8位组合,而不使用任何库(如果有必要的话,除了位集)。如果我这样做的话,我将得到8 for循环,这有点多了。我想知道是否有一种使用递归或使用标准do/while/for循环的巧妙技巧来压缩这个循环。
发布于 2017-05-21 22:32:27
这个任务可以通过简单的for循环和二进制操作来完成。比特移位i的数量,然后& 1,以掩盖该位。
#include <iostream>
void printBinary()
{
for(int i = 0; i < 256; i++){
for(int bit = 7; bit >= 0; bit--){
std::cout << (i >> bit & 1);
}
std::cout << std::endl;
}
}发布于 2017-05-21 22:17:12
首先,您的循环是不正确的:它们运行在0到7之间,包含在内,而它们应该从0运行到1,包括在内,因为位不是0,就是1。
就所有8位组合而言,您可以使用一个循环:使用从0到255的int计数,包括在内,并打印其二进制表示:
for (int i = 0 ; i != 256 ; i++) {
cout << bitset<8>(i).to_string() << endl;
}https://stackoverflow.com/questions/44102302
复制相似问题