这是 Long 中 rotateLeft 的实现:
public static long rotateLeft(long i, int distance) {
return (i << distance) | (i >>> -distance);
}
但是,我不明白 (i >>> -distance) 是如何工作的!谁能告诉我怎么做!谢谢。
最佳答案
只取移位值的最低位。
这和
是一样的return (i << (distance & 63)) | (i >>> (-distance & 63));
或
return (i << (distance & 63)) | (i >>> ((64-distance) & 63));
或
return (i << distance) | (i >>> (64-distance));
使用负数的一个原因是它与类型无关,因此您可以在将来安全地更改它。
例如
// This works regardless of whether `x` is `int` or `long`
// and you can safely change the type in the future.
// 1 if negative, 0 if non-negative
x >>> -1;
// works for 32-bit but not 64-bit so if you change the type later,
// it could break without compiler error.
x >>> 31;
您可能会发现这很有趣 http://vanillajava.blogspot.com/2012/01/shifting-challenge.html
关于java - (i >>> -distance) 是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9513074/