当前位置: 代码迷 >> 综合 >> bilibili-2020算法笔试第一题-输出数组拼接最大数
  详细解决方案

bilibili-2020算法笔试第一题-输出数组拼接最大数

热度:58   发布时间:2023-12-17 03:20:27.0
''' 输入一组非负数, 输出这些数的拼接,保证该拼接后的数最大 input 20,203 output 20320 '''
import sys
def split_number(number):''':param number: 123:return: [1, 2, 3]'''length = len(str(number))i = length-1str_num = [0 for i in range(length)]n = numberwhile n > 0:temp = n % 10str_num[i] = tempi -= 1n = (n-temp) // 10return str_numdef who_is_first(num1, num2):num1_char = split_number(num1)  #num2_char = split_number(num2)flag = Truelength_num1 = len(num1_char)  # 第一个数的位数length_num2 = len(num2_char)  # 第二个数的位数i = 0j = 0while i < length_num1 and j < length_num2 :if num1_char[i] < num2_char[j]:flag = Falsereturn flagelif num1_char[i] == num2_char[j] and length_num1 != length_num2:if i == len(num1_char)-1:  # 第一个数比较短,再看第二个数的第(length_num1+1)个数是否比第一个数的第一位大if num2_char[(length_num1+1)-1] > num1_char[0]:flag = Falseelse:flag = Truereturn flagelif j == len(num2_char)-1:  # 第二个数比较短if num1_char[(length_num2+1)-1] > num2_char[0]:  # 第二个数比较短,再看第一个数的第(length_num2+1)个数是否比第二个数的第一位大flag = Trueelse:flag = Falsereturn flagelse:flag = Truereturn flagi += 1j += 1return flagdef my_sort(numbers):'''指定规则排序 选择排序法:param numbers::return:'''for i in range(0, len(numbers)-1):the_first = ifor j in range(i+1, len(numbers)):if who_is_first(numbers[j], numbers[the_first]):the_first = jtemp = numbers[i]numbers[i] = numbers[the_first]numbers[the_first] = tempreturn numbers
numbers = list(map(int, input().split(',')))for num in my_sort(numbers):sys.stdout.write(str(num))