题解 | #字符串合并处理#

字符串合并处理

https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f

# 下标奇数和下标偶数分别排序
# 十六进制转二进制,二进制倒序后转十六进制

str1 = input().split()
str2 = str1[0] + str1[1]
str2 = [i for i in str2]  # 转成单个字符列表
list1 = []  # 存奇数索引的数
list2 = []  # 存偶数索引的数
for index, i in enumerate(str2):
    if index % 2 == 0:
        list2.append(i)
    else:
        list1.append(i)
list1 = sorted(list1, reverse=False)
list2 = sorted(list2, reverse=False)
count_1 = 0 # 偶数位索引
count_2 = 0 # 奇数位索引
for index, i in enumerate(str2):
    if index % 2 == 0:
        str2[index] = list2[count_1]
        count_1 += 1
    if index % 2 == 1:
        str2[index] = list1[count_2]
        count_2 += 1
str2 = "".join(str2)
# print(str2)
str2 = [i for i in str2]
new_str2 = []
for i in str2:
    # 如果是字母,并且不是十六进制的字母,保持原样,否则,按照规则进行转换
    if i.upper() not in ["A", "B", "C", "D", "E", "F"] and i.isalpha():
        new_str2.append(i)
    else:
        tep = (bin(int(i, 16))[2:])  # 先转成10进制,再转成2进制
        # 这题要补0
        if len(tep) == 3:
            tep = "0" + tep
        if len(tep) == 2:
            tep = "00" + tep
        if len(tep) == 1:
            tep = "000" + tep
        new = hex(int(tep[::-1], 2))[2:]
        if new.isalpha():
            new = new.upper()
        new_str2.append(new)

print("".join(new_str2))

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务