我需要对此代码进行一些解释。 这是其他人给出的示例代码。`check/= 2;'的说明`
for (int i = 1; i <= 8; i++)
{
if(check % 2 == 0)
sum += i;
else
sum -= i;
check /= 2; <--- Need explanation for this line.
}
但在Pseudo code
,没有check /= 2;
程序。
这是完整的Pseudo code
。
int binary = 0;
int sum;
while(binary<256)
sum = 0;
for(go through all 8 digits)
if the i-th digit is 0
sum += i
if the i-th digit is 1
sum -= i
end for
if sum == 0
output
binary++
end while
那么,这行代码的目的是什么?
由于sum
,binary
和check
初始化为0
。
我已经使用上面给出的伪代码编写了此代码。 但似乎我的代码将复制输出和一个更多的问题,格式。
我想要的输出是这样的格式:
Enter a number : 3
-1 -2 +3 = 0
1 +2 -3 = 0
但我目前输出:
Enter a number : 3
-1 -2 3 = 0
1 2 -3 = 0
这里是我的代码:
CODE IS REMOVED!
解决了!
我太专注于输出部分的for
-loop,因此错过了二进制的while
-loop,因为伪代码用于256个可能的解决方案,因此前端部分将有相同的输出,例如:
1 - 2 - 3 + 4 = 0
1 - 2 - 3 + 4 + 5 - 6 - 7 + 8 = 0
因此,伪代码可能会给出相同的输出。所以,因为该解决方案是在2^n
其中n = 1, 2, 3, ...
形式,所以更改
while(binary < 256) ---> while (binary < Math.pow(2, input))
应该解决这个问题。
解决了答案的格式和副本。
谁是“他人”?代码应该做什么? – 2012-04-12 07:42:18
我在'yahoo.answer.com'中被问到了,其中一个答复给了我这个示例代码,那个“其他人”。 该代码是为状态空间查找所有可能的解决方案。 – Chin 2012-04-12 07:59:20