Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
002.add_two_numbers (Medium)
links:
Title: https://oj.leetcode.com/problems/add-two-numbers/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
A new list that is generated by adding two lists.
Analysis:
Direct simulation is possible.
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%; Sum/= ten; 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%; Sum/= ten; 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% sum/= if L1! = None or L2! = None or sum!! = 0: cur.next = ListNode (0) C16/>cur = Cur.next else: break return ret
[Leetcode] 002. Add Numbers (Medium) (C++/java/python)