2、Add Two Numbers
来源:互联网 发布:阿里巴巴 淘宝 便宜 编辑:程序博客网 时间:2024/06/05 21:54
题目描述:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
思路:
把链表中数据转换为整数相加,将结果放入链表中输出
当前解法:
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # 将链表中的数转换到list中 list1 = [] list2 = [] while l1 is not None: list1.append(l1.val) l1 = l1.next while l2 is not None: list2.append(l2.val) l2 = l2.next # 将list两个整数相加 num1 = 0 num2 = 0 for i in range(len(list1) - 1, -1, -1): num1 = num1 * 10 + list1[i] for j in range(len(list2) - 1, -1, -1): num2 = num2 * 10 + list2[j] num3 = num1 + num2 # 将num3写入链表返回 l3 = ListNode(None) l3.val = num3 % 10 temp = l3 while num3 >= 10: num3 = num3 // 10 temp.next = ListNode(None) temp.next.val = int(num3) % 10 temp = temp.next return l3
阅读全文