2012-03-01 1 views
3

を作業これはロングでrotateLeftのimplecationです:私は、(i >>> -distance)動作しませ方法を理解することはできません、どうするか(私は-distanceを>>>)

public static long rotateLeft(long i, int distance) { 
    return (i << distance) | (i >>> -distance); 
} 

けど!どのように私に教えることができる誰か!ありがとうございました。

答えて

7

シフト値の最下位ビットだけが使用されます。

負の数を使用する

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; 

あなたは、私はOPが負の数の作品にシフトする方法を知りたいと思うこの興味深いhttp://vanillajava.blogspot.com/2012/01/shifting-challenge.html

+0

負の数でシフトを説明する+1: –

+0

ありがとう!コンパイル時にjvmは(-distance&63)に移動しますか?それは正しい? – liuxiaori

+0

いいえ、JVMがそれをどのように実装しているかは、正か負かです。 「1L << 64」も「1L」になります –

0

>>>は、unsigned right shift operatorです。

符号なし右シフト演算子 ">>>"は、ゼロを一番左の位置にシフトします。

+3

を見つけるかもしれません。 –

+0

右ですが、皆さんにありがとうございます。 – liuxiaori

関連する問題