文章目录
- 1 Introduction
- 2 Code
- 2.1 Output
- 2.2 复杂度分析
- 参考资料
Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end.
In the left rotation, the bits that fall off at the left end are put back at the right end.
In the right rotation, the bits that fall off at the right end are put back at the left end.
1 Introduction
循环位移:rotate the bits。
Bit rotation, also known as bit shifting, is a technique for rotating the bits of a binary number to the left or right. This can be useful in a variety of contexts, such as in computer science and cryptography.
2 Code
# Python3 code to
# rotate bits of numberINT_BITS = 32# Function to left
# rotate n by d bits
def leftRotate(n, d):# In n<<d, last d bits are 0.# To put first 3 bits of n at # last, do bitwise or of n<<d# with n >>(INT_BITS - d) return (n << d)|(n >> (INT_BITS - d))# Function to right
# rotate n by d bits
def rightRotate(n, 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)) & 0xFFFFFFFF# Driver program to
# test above functions
n = 16
d = 2print("Left Rotation of",n,"by",d,"is",end=" ")
print(leftRotate(n, d))print("Right Rotation of",n,"by",d,"is",end=" ")
print(rightRotate(n, d))# This code is contributed by
# Smitha Dinesh Semwal
2.1 Output
Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4
2.2 复杂度分析
Time Complexity: O(1)
Auxiliary Space: O(1)
参考资料
[1] https://www.geeksforgeeks.org/python3-program-to-rotate-bits-of-a-number/
[2] https://www.geeksforgeeks.org/rotate-bits-of-an-integer/