给定两个正整数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.
方法:可以使用set和Python的列表解决问题。请按照以下步骤解决问题:
- 将两个整数都转换为字符串。
- 现在,使用map()函数将字符串A和B的字符的等效整数值存储在列表lis1和lis2中。
- 都转换列表LIS1和LIS2到集LIS1和LIS2使用set()方法。
- 现在,使用函数symmetric_difference()找到两个集合lis1和lis2的不常见数字,并将其存储在集合中,例如lis 。
- 完成上述步骤后,使用list()方法将set lis转换为list 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))