如何将一个数除3而不使用*、/、+、-、%等运算符?
号码可以有签名,也可以没有签名。
如何将一个数除3而不使用*、/、+、-、%等运算符?
号码可以有签名,也可以没有签名。
当前回答
要将一个32位数字除以3,可以将其乘以0x55555556,然后取64位结果的前32位。
现在剩下要做的就是使用位运算和移位来实现乘法…
其他回答
Yet another solution. This should handle all ints (including negative ints) except the min value of an int, which would need to be handled as a hard coded exception. This basically does division by subtraction but only using bit operators (shifts, xor, & and complement). For faster speed, it subtracts 3 * (decreasing powers of 2). In c#, it executes around 444 of these DivideBy3 calls per millisecond (2.2 seconds for 1,000,000 divides), so not horrendously slow, but no where near as fast as a simple x/3. By comparison, Coodey's nice solution is about 5 times faster than this one.
public static int DivideBy3(int a) {
bool negative = a < 0;
if (negative) a = Negate(a);
int result;
int sub = 3 << 29;
int threes = 1 << 29;
result = 0;
while (threes > 0) {
if (a >= sub) {
a = Add(a, Negate(sub));
result = Add(result, threes);
}
sub >>= 1;
threes >>= 1;
}
if (negative) result = Negate(result);
return result;
}
public static int Negate(int a) {
return Add(~a, 1);
}
public static int Add(int a, int b) {
int x = 0;
x = a ^ b;
while ((a & b) != 0) {
b = (a & b) << 1;
a = x;
x = a ^ b;
}
return x;
}
这是c#,因为这是我手边的东西,但与c的区别应该很小。
通过使用eval和字符串连接来在“幕后”使用/操作符是欺骗吗?
例如,在Javacript中,您可以这样做
function div3 (n) {
var div = String.fromCharCode(47);
return eval([n, div, 3].join(""));
}
并不是所有的答案都是面试官想听到的:
我的回答:
“我绝不会那样做,谁会为这种愚蠢的事情付出代价呢?”没有人 会有一个优势,它不是更快,它只是愚蠢。 教授设计师必须知道这一点,但这必须适用于所有数字,而不仅仅是除以3。”
要将一个32位数字除以3,可以将其乘以0x55555556,然后取64位结果的前32位。
现在剩下要做的就是使用位运算和移位来实现乘法…
很好bc:
$ num=1337; printf "scale=5;${num}\x2F3;\n" | bc
445.66666