Python3程序将给定数字的数字旋转K
给定两个整数N和K ,任务是将N的数字旋转 K。如果K是正整数,则左旋转其数字。否则,右旋转它的数字。
例子:
Input: N = 12345, K = 2
Output: 34512
Explanation:
Left rotating N(= 12345) by K(= 2) modifies N to 34512.
Therefore, the required output is 34512
Input: N = 12345, K = -3
Output: 34512
Explanation:
Right rotating N(= 12345) by K( = -3) modifies N to 34512.
Therefore, the required output is 34512
解决方法:按照以下步骤解决问题:
- 初始化一个变量,比如X ,以存储N中的位数。
- 更新K = (K + X) % X以将其减少为左旋转的情况。
- 删除N的前K个数字,并将所有删除的数字附加到N的数字的右侧。
- 最后,打印N的值。
下面是上述方法的实现:
Python3
# Python3 program to implement
# the above approach
# Function to find the count of
# digits in N
def numberOfDigit(N):
# Stores count of
# digits in N
digit = 0
# Calculate the count
# of digits in N
while (N > 0):
# Update digit
digit += 1
# Update N
N //= 10
return digit
# Function to rotate the digits of N by K
def rotateNumberByK(N, K):
# Stores count of digits in N
X = numberOfDigit(N)
# Update K so that only need to
# handle left rotation
K = ((K % X) + X) % X
# Stores first K digits of N
left_no = N // pow(10, X - K)
# Remove first K digits of N
N = N % pow(10, X - K)
# Stores count of digits in left_no
left_digit = numberOfDigit(left_no)
# Append left_no to the right of
# digits of N
N = N * pow(10, left_digit) + left_no
print(N)
# Driver Code
if __name__ == '__main__':
N, K = 12345, 7
# Function Call
rotateNumberByK(N, K)
# This code is contributed by mohit kumar 29
输出:
34512
时间复杂度: O(log 10 N)
辅助空间: O(1)
有关详细信息,请参阅有关将给定数字的数字旋转 K 的完整文章!