|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:
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.
C++
- class Solution {
- public:
- ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
- ListNode *ret = new ListNode(0);
- ListNode *cur = ret;
- int sum = 0;
- while (1) {
- if (l1 != NULL) {
- sum += l1->val;
- l1 = l1->next;
- }
- if (l2 != NULL) {
- sum += l2->val;
- l2 = l2->next;
- }
- cur->val = sum % 10;
- sum /= 10;
- if (l1 != NULL || l2 != NULL || sum)
- cur = (cur->next = new ListNode(0));
- else
- break;
- }
- return ret;
- }
- };
复制代码
Python
- # Definition for singly-linked list.
- # class ListNode:
- # def __init__(self, x):
- # self.val = x
- # self.next = None
- class Solution:
- def addTwoNumbers(self, l1, l2):
- """
- :type l1: ListNode
- :type l2: ListNode
- :rtype: ListNode
- """
- a=0
- s=l1
- t=l2
- while s.next!=None or t.next!=None:
- if s.next == None:
- s.next=ListNode(0)
- if t.next == None:
- t.next=ListNode(0)
- b = (s.val+t.val+a)//10
- s.val = (s.val+t.val+a)%10
- a=b
- s=s.next
- t=t.next
- b = (s.val+t.val+a)//10
- s.val = (s.val+t.val+a)%10
- a=b
- if a!=0:
- s.next=ListNode(1)
- return l1
复制代码 |
|