
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Two Numbers in Python
Suppose we have given two non-empty linked lists. These two lists are representing two non-negative integer numbers. The digits are stored in reverse order. Each of their nodes contains only one digit. Add the two numbers and return the result as a linked list. We are taking the assumption that the two numbers do not contain any leading zeros, except the number 0 itself. So if the numbers are 120 + 230, then the linked lists will be [0 → 2 → 1] + [0 → 3 → 2] = [0 → 5 → 3] = 350.
To solve this, we will follow these steps
- Take two lists l1 and l2. Initialize head and temp as null
- c := 0
- while l1 and l2 both are non-empty lists
- if l1 is non-empty, then set a := 0, otherwise set a := l1.val
- if l2 is non-empty, then set b := 0, otherwise set b := l2.val
- n := a + b + c
- if n > 9, then c := 1 otherwise 0
- node := create a new node with value n mod 10
- if head is null
head := node and temp := node
- otherwise
- head.next := node, and head := node
- l1 := next node of l1, if l1 exists
- l2 := next node of l2, if l2 exists
- if c is non-zero, then
- node := new node with value 1, next of head := node
- return temp
Example(Python)
Let us see the following implementation to get a better understanding
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = None temp = None c = 0 while l1 or l2: if not l1: a= 0 else: a = l1.val if not l2: b=0 else: b = l2.val n = a +b + c c = 1 if n>9 else 0 node = ListNode(n%10) if not head: head = node temp = node else: head.next = node head = node l1 = l1.next if l1 else None l2 = l2.next if l2 else None if c: node = ListNode(1) head.next = node return temp ob1 = Solution() l1 = make_list([0,2,1]) l2 = make_list([0,3,2]) print_list(ob1.addTwoNumbers(l1, l2))
Input
[0,2,1] [0,3,2]
Output
[0,5,3]
Advertisements