(注意:请参阅下面的编辑 2 以获得更好的版本!)
这并不像听起来那么棘手,因为您说过“不使用 [..] + [..] operators”。如果您想禁止同时使用+ 字符,请参见下文。
unsigned div_by(unsigned const x, unsigned const by) {
unsigned floor = 0;
for (unsigned cmp = 0, r = 0; cmp <= x;) {
for (unsigned i = 0; i < by; i++)
cmp++; // that's not the + operator!
floor = r;
r++; // neither is this.
}
return floor;
}
然后只需说出div_by(100,3) 即可将100 除以3。
编辑:您也可以继续替换 ++ 运算符:
unsigned inc(unsigned x) {
for (unsigned mask = 1; mask; mask <<= 1) {
if (mask & x)
x &= ~mask;
else
return x & mask;
}
return 0; // overflow (note that both x and mask are 0 here)
}
编辑 2:稍快的版本不使用任何包含 +,-,*,/,% 字符的运算符。
unsigned add(char const zero[], unsigned const x, unsigned const y) {
// this exploits that &foo[bar] == foo+bar if foo is of type char*
return (int)(uintptr_t)(&((&zero[x])[y]));
}
unsigned div_by(unsigned const x, unsigned const by) {
unsigned floor = 0;
for (unsigned cmp = 0, r = 0; cmp <= x;) {
cmp = add(0,cmp,by);
floor = r;
r = add(0,r,1);
}
return floor;
}
我们使用add 函数的第一个参数,因为不使用* 字符就无法表示指针的类型,除非在函数参数列表中,其中type[] 的语法与type* const 相同。
FWIW,您可以使用与AndreyT 提出的0x55555556 技巧类似的技巧轻松实现乘法函数:
int mul(int const x, int const y) {
return sizeof(struct {
char const ignore[y];
}[x]);
}