给定一个整数N,表示为X = 16位的二进制表示。我们还得到了一个数字“ m”和一个字符L,该字符c可以是L或R。任务是确定一个数字M,该数字是在c = L或n的情况下向左循环移位N个二进制表示形式的m个位置之后生成的如果c =R。
例子:
Input : N = 7881, m = 5, c = L
Output : 55587
Explanation:
N in binary is 0001 1110 1100 1001 and shifting it left by 5 positions, it becomes 1101 1001 0010 0011 which in the decimal system is 55587.
Input : N = 7881, m = 3, c = R
Output : 9177
Explanation:
N in binary is 0001 1110 1100 1001 and shifted 3 positions to right, it becomes 0010 0011 1101 1001 which in the decimal system is 9177.
方法:
为了解决上述问题,我们观察到,如果char为R,则必须将数字右移m;如果char为L,则将m左移,其中左移等于将数字乘以2。右移等效于将数字除以2。
下面是上述方法的实现:
# Python implementation to make
# Cyclic shifts of integer N by another integer m
def Count(N, count, turn):
# Convert N into hexadecimal number and
# remove the initial zeros in it
N = hex(int(N)).split('x')[-1]
# Convert hexadecimal term binary
# string of length = 16 with padded 0s
S = ( bin(int(N, 16))[2:] ).zfill(16)
# rotate the string by a specific count
if(turn == 'R'):
S = (S[16 - int(count) : ] + S[0 : 16 - int(count)])
else:
S = (S[int(count) : ] + S[0 : int(count)])
# Convert the rotated binary string
# in decimal form, here 2 means in binary form.
print(int(S, 2))
# driver code
N = 7881
count = 5
turn = 'L'
Count(N, count, turn)
输出:
55587