1.两数相加
https://leetcode-cn.com/problems/add-two-numbers/
自己的代码能力果然很差,写出来直接超时。
1 # Definition for singly-linked list. 2 3 class ListNode(object): 4 def __init__(self, val=0, next=None): 5 self.val = val 6 self.next = next 7 8 class Solution(object): 9 def addTwoNumbers(self, l1, l2): 10 """ 11 :type l1: ListNode 12 :type l2: ListNode 13 :rtype: ListNode 14 """ 15 l1_val = 0 16 l1_len = 0 17 while(l1.next != None): 18 l1_val += l1.val * (10 ** l1_len) 19 l1_len += 1 20 21 l2_val = 0 22 l2_len = 0 23 while(l2.next != None): 24 l2_val += l2.val * (10 ** l2_len) 25 l2_len += 1 26 27 res_list = [] 28 res_last_val = 0 29 res_val = l1_val + l2_val 30 res_len = max(l1_len, l2_len) 31 for i in range(1, res_len+1): 32 res_list.append(ListNode((res_val-res_last_val)//(10**(res_len-i)))) 33 res_last_val = (res_val-res_last_val)//(10**(res_len-i)) * (10**(res_len-i)) 34 35 for i in range(res_len-1): 36 res_list[i].next = res_list[i+1] 37 38 res = res_list[0] 39 return res
看了官方代码和大神答案,感觉自己还得好好研究研究
2.