功能给出了错误的结果
问题描述:
我试过写下面的函数,通过从算法文本中翻译算法来生成一个字符串的所有组合。但它会在所有组合的输出中保留打印整个字符串。功能给出了错误的结果
len = strlen(str);
for(i=0;i<pow(2,len);i++)
{
for(j=0;j<len;j++)
{
if(i && (0x1 << j))
{
cout<<str[j];
}
}
cout<<endl;
}
谢谢大家。
答
既然要检查j
位被变量i
设置您需要使用按位&
运营商,而不是逻辑&&
:
if(i && (0x1 << j))
^^
+0
它的工作表示感谢。他们有什么区别? – user664982 2011-03-17 19:46:00
+0
你会发现这个很有用:http://stackoverflow.com/questions/5051349/what-is-the-difference-bettween-bitwise-and-and-logical-and – codaddict 2011-03-17 19:57:39
由于这是C++,喜欢用'STD: :字符串到'char *'。获取'std :: string'的长度比在'char *'中扫描''\ 0''快。另外,'std :: string'更安全并且可以增长。 – 2011-03-17 19:45:44
感谢提示Thomas。 – user664982 2011-03-17 19:47:13
@Thomas Matthews:你意识到'(len * len)'不能代替'pow(2,len)',对吧? – Blastfurnace 2011-03-18 04:46:22