给定两个正整数A和B ,任务是按降序打印不同的数字,这两个数字不常见。
例子:
Input: A = 378212, B = 78124590
Output: 9 5 4 3 0
Explanation: All distinct digits present in the two numbers are {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. The digits {1, 2, 6, 7} are common in both numbers.
Input: A = 100, B = 273
Output: 7 3 2 1 0
Explanation: All distinct digits present in the two numbers are {0, 1, 2, 3, 7}. The digits {0, 1, 2, 3, 7} are common in both numbers.
方法:可以使用Python的集合和列表来解决这个问题。请按照以下步骤解决问题:
- 将两个整数都转换为字符串。
- 现在,使用 map()函数将字符串A和B的字符的等效整数值存储在列表lis1和lis2 中。
- 使用 set() 方法将列表lis1和lis2转换为设置lis1和lis2 。
- 现在,使用函数symmetric_difference() 找到集合lis1和lis2的不常见数字并将其存储在集合中,例如lis 。
- 完成上述步骤后,使用 list() 方法将集合lis转换为列表lis 。
- 最后,按降序对列表进行排序并打印列表lis作为答案。
下面是上述方法的实现:
Python3
# Python implementation
# of the above approach
# Function to print uncommon digits
# of two numbers in descending order
def disticntUncommonDigits(A, B):
# Stores digits of A as string
A = str(A)
# Stores digits of B as string
B = str(B)
# Stores the characters
# of A in a integer list
lis1 = list(map(int, A))
# Stores the characters
# of B in a integer list
lis2 = list(map(int, B))
# Converts lis1 to set
lis1 = set(lis1)
# Converts lis2 to set
lis2 = set(lis2)
# Stores the uncommon digits present
# in the sets lis1 and lis2
lis = lis1.symmetric_difference(lis2)
# Converts lis to list
lis = list(lis)
# Sort the list in descending order
lis.sort(reverse = True)
# Print the list lis
for i in lis:
print(i, end =" ")
# Driver Code
# Input
A = 378212
B = 78124590
disticntUncommonDigits(A, B)
输出:
9 5 4 3 0
时间复杂度: O(log 10 (A) + log 10 (B))
辅助空间: O(log 10 (A) + log 10 (B))
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live