以下哪一种技术是整数除2的最佳选择,为什么?
技巧1:
x = x >> 1;
技巧2:
x = x / 2;
这里x是整数。
以下哪一种技术是整数除2的最佳选择,为什么?
技巧1:
x = x >> 1;
技巧2:
x = x / 2;
这里x是整数。
当前回答
我说这些是为了参加编程比赛。一般来说,他们有非常大的输入,除以2会发生很多次,已知输入是正的或负的。
X >>1比X /2好。我在ideone.com上运行了一个程序,其中发生了超过10^10除以2的运算。X /2花了将近5.5s,而X >>1花了将近2.6s。
其他回答
哪一个是最好的选择,为什么整数除以2?
这取决于你对最佳的定义。
如果你想让你的同事讨厌你,或者让你的代码难以阅读,我肯定会选择第一个选择。
如果你想把一个数除以2,就用第二个数。
这两者是不等价的,如果数字是负的或在更大的表达式中,它们的行为是不一样的——bitshift的优先级比+或-低,除法的优先级更高。
您应该编写代码来表达其意图。如果您关心的是性能,不要担心,优化器在这类微优化方面做得很好。
X/Y是正确的…和" >> "移位运算符..如果我们想要二除一个整数,我们可以使用(/)被除数运算符。移位运算符用于移位位。
x = x / 2; x / = 2;我们可以这样用…
使用除法(/),假设这样更清楚。编译器将相应地进行优化。
就CPU而言,位移运算比除法运算快。 然而,编译器知道这一点,并将适当地优化到它可以的程度, 因此,您可以以最有意义的方式编写代码,并且知道您的代码是有意义的 有效地运行。但是请记住,由于前面指出的原因,在某些情况下,无符号整型可以比整型更好地优化。 如果你不需要符号算术,那么不要包含符号位。
这个问题的答案取决于你工作的环境。
If you're working on an 8-bit microcontroller or anything without hardware support for multiplication, bit shifting is expected and commonplace, and while the compiler will almost certainly turn x /= 2 into x >>= 1, the presence of a division symbol will raise more eyebrows in that environment than using a shift to effect a division. If you're working in a performance-critical environment or section of code, or your code could be compiled with compiler optimization off, x >>= 1 with a comment explaining its reasoning is probably best just for clarity of purpose. If you're not under one of the above conditions, make your code more readable by simply using x /= 2. Better to save the next programmer who happens to look at your code the 10 second double-take on your shift operation than to needlessly prove you knew the shift was more efficient sans compiler optimization.
所有这些假设都是无符号整数。简单的移位可能不是你想要的符号。此外,DanielH提出了一个关于在ActionScript等特定语言中使用x *= 0.5的好观点。