[LeetCode] 002. Add Two Numbers (Medium) (C ++/Java/Python), leetcodepython
Index: [LeetCode] Leetcode index (C ++/Java/Python/SQL)
Github: https://github.com/illuz/leetcode
002. Add_Two_Numbers (Medium)
Link:
Title: https://oj.leetcode.com/problems/add-two-numbers/
Code (github): https://github.com/illuz/leetcode
Question:
Calculate a new List generated by adding two lists.
Analysis:
Directly simulate it.
Code:
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; }};
Java:
public class Solution { // Definition for singly-linked list. public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode ret = new ListNode(0); ListNode cur = ret; int sum = 0; while (true) { 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 != 0) { cur = (cur.next = new ListNode(0)); } else { break; } } return ret; }}
Python:
class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): ret = ListNode(0) cur = ret sum = 0 while True: if l1 != None: sum += l1.val l1 = l1.next if l2 != None: sum += l2.val l2 = l2.next cur.val = sum % 10 sum /= 10 if l1 != None or l2 != None or sum != 0: cur.next = ListNode(0) cur = cur.next else: break return ret