编写程序打印 a 到 z 中任取 3 个元素的组合(比如 打印 a b c ,d y z等)
思路:a - z 每个字母给一个标记 0 或 1 ,1表示在组合,0表示不在,一共16个标记位。
- 一个变量都不在组合中时,就是 26 个 0
- 所有变量都在组合中中时,就是 26 个 1
把0到26个1看成数字,就是0和(1 << 26) - 1,那么其它的组合,为0 到 (1 << 26) - 1 之间的数字,例如:
cba 就是 …00000000111dcba 就是 …0000001111
循环 从 0 开始 到(1 << 26) - 1 ,然后只取有 3 个 1 的数字 ,再看对应的 1 代表哪个字符就打印了
代码:
#include <stdio.h>
//某个数二进制位上有几个 1
int bit(unsigned int x)
{
int c = 0;
while( x )
{
c++;
x = (x & (x - 1));
}
return c;
}
void print(unsigned int x, int count)
{
int i = 0;
//控制,假如count为3, x 里边有三个 1
if( bit(x) == count )
{
for(i=0; i<26; i++)
{
if( x & 1)
{
printf("%c ", (char)('a' + i));
}
x = (x >> 1);
}
printf("\n");
}
}
int main()
{
const unsigned int N = 26;
const unsigned int C = 3;
const unsigned int X = (1 << N) - 1; //X=(1<<26)-1
unsigned int i = 0;
for(i=0; i<X; i++)
{
print(i, C);
}
return 0;
}
博客介绍如何编写程序来打印从A到Z中任意选取三个字母的所有可能组合,通过为每个字母分配0或1的标记来实现。

2811

被折叠的 条评论
为什么被折叠?



