GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Linked Lists/add_two_numbers.py at master · cemalsenel/coding-problems Expand file tree/ Copy pathadd_two_numbers.pyMore file actions 74 lines (57 loc) · 1.83 KB / Copy pathadd_two_numbers.pyFile metadata and controls74 lines (57 loc) · 1.83 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 ''' Add Two Numbers 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. Input: 2 -> 4 -> 3, 5 -> 6 -> 4 Output: 7 -> 0 -> 8 Output explanation: 342 + 465 = 807 ========================================= Iterate LL and add values on same position (just like adding real numbers). Time Complexity: O(N) Space Complexity: O(1) ''' ############ # Solution # ############ # import ListNode class from ll_helpers.py from ll_helpers import ListNode def add_two_numbers(l1, l2): start = ListNode(None) # use the same linked list as result so the Space complexity will be O(1) start.next = l1 pointer = start transfer = 0 while (l1 is not None) or (l2 is not None) or (transfer != 0): v1 = 0 if l1 is not None: v1 = l1.val l1 = l1.next v2 = 0 if l2 is not None: v2 = l2.val l2 = l2.next total = transfer + v1 + v2 transfer = total // 10 if l1 is None: # if the first list is shorter than the second, add new elements at the end pointer.next = ListNode(None) pointer = pointer.next pointer.val = total % 10 return start.next ########### # Testing # ########### # import build_ll and print_ll methods from ll_helpers.py from ll_helpers import build_ll, print_ll # Test 1 # Correct result => 7 -> 0 -> 8 ll1 = build_ll([2, 4, 3]) ll2 = build_ll([5, 6, 4]) print_ll(add_two_numbers(ll1, ll2)) # Test 2 # Correct result => 8 -> 9 -> 0 -> 0 -> 1 ll1 = build_ll([9, 9, 9, 9]) ll2 = build_ll([9, 9]) print_ll(add_two_numbers(ll1, ll2)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |