Java程序旋转数字的位
位旋转:旋转(或循环移位)是一种类似于移位的操作,不同之处在于将一端脱落的位放回另一端。
在左旋转中,在左端脱落的位被放回右端。
在右旋转中,在右端脱落的位被放回左端。
例子:
让 n 使用 8 位存储。将 n = 11100101 左旋转 3 使 n = 00101111 (左移 3 位,前 3 位放回 last )。如果 n 使用 16 位或 32 位存储,则 n (000…11100101) 的左旋转变为 00..00 11100101 000。
如果 n 使用 8 位存储,则将 n = 11100101 右旋转 3 使得 n = 10111100 (右移 3 并且最后 3 位首先放回)。如果 n 使用 16 位或 32 位存储,则 n (000…11100101) 右旋转 3 变为101 000..00 11100 。
Java
// Java code to rotate bits
// of number
class GFG
{
static final int INT_BITS = 32;
/*Function to left rotate n by d bits*/
static int leftRotate(int n, int d) {
/* In n<>(INT_BITS - d) */
return (n << d) | (n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
static int rightRotate(int n, int d) {
/* In n>>d, first d bits are 0.
To put last 3 bits of at
first, do bitwise or of n>>d
with n <<(INT_BITS - d) */
return (n >> d) | (n << (INT_BITS - d));
}
// Driver code
public static void main(String arg[])
{
int n = 16;
int d = 2;
System.out.print("Left Rotation of " + n +
" by " + d + " is ");
System.out.print(leftRotate(n, d));
System.out.print("
Right Rotation of " + n +
" by " + d + " is ");
System.out.print(rightRotate(n, d));
}
}
// This code is contributed by Anant Agarwal.
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
int N=28;
int D=2;
rotate(N,D);
}
static void rotate(int N, int D)
{
// your code here
int t=16;
int left= ((N<>(t-D)) & 0xFFFF;
int right=((N>>D) | N<<(t-D)) & 0xFFFF;
System.out.println(left);
System.out.println(right);
}
}
输出 :
Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4
对于 16 位数字:
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
int N=28;
int D=2;
rotate(N,D);
}
static void rotate(int N, int D)
{
// your code here
int t=16;
int left= ((N<>(t-D)) & 0xFFFF;
int right=((N>>D) | N<<(t-D)) & 0xFFFF;
System.out.println(left);
System.out.println(right);
}
}
输出:
Left Rotation of 28 by 2 is 112
Right Rotation of 28 by 2 is 7
时间复杂度:O(1)
空间复杂度:O(1)
有关更多详细信息,请参阅有关旋转位数的完整文章!