给定一个整数N,表示为X = 16位的二进制表示。我们还给出了一些“m”和一个字符c是L或R的任务是确定被后的任何左米的位置循环移位N的二进制表示中产生的数量M如果c = L或右如果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
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。