我需要编写一个函数来计算传入的无符号整数的以16为底的对数的最大整数值。我们有使用哪些运算符和常量的限制,并且只能使用特定的for
循环。
为了清晰起见,我们不能使用任何条件语句(if、else、switch ...)。函数原型如下:
int floor_log16(unsigned int x);
Allowed operators:
++
--
=
&
|
~
^
<<
!
>>
Allowed constants: 1
2
3
4
8
16
我编写了如下版本的程序:
int floor_log16(unsigned int x) {
int index=1;
int count=(1!=1);
count--;
for(; index<=x; index<<=4) {
count++;
}
return count;
}
这段代码似乎按照预期工作。然而,根据后续需要编写的功能函数和描述,我注意到在“允许使用的运算符”下有时会列出>
和<
。
我推断这意味着,由于上面列出的floor_log16
函数没有明确告诉我们要使用>
或<
,我只能假设上面发布的解决方案将不被接受。
这让我感到困惑,因为我不明白怎么可能没有布尔检查就进行for循环呢?
难道循环的整个想法不是在满足条件的情况下进行迭代吗?
else
)-if(condition) statement;
=for(;condition;) {statement; break;}
,但我不认为这是您要做的。 - Bernhard Barkerfor(;x;x>>4)
的语法?这样当x == 0
时循环将停止。 - Soufiane Hassouint count = (1 != 1)
... "!=" 不是允许的运算符。index <<= 4
... 也不是允许的运算符,但index = index << 4
是可以的。 - Jim Balter