LeetCode Add Two Numbers Problem Solution in Java
/*
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int result = 0;
ListNode newans = new ListNode(0);
ListNode p1 = l1,p2 = l2, l3 = newans;
while(p1!=null || p2!=null){
if(p1!=null){
result += p1.val;
p1 = p1.next;
}
if(p2!=null){
result+= p2.val;
p2= p2.next;
}
l3.next = new ListNode(result%10);
l3 = l3.next;
result = result/10;
}
if(result == 1 ){
l3.next = new ListNode(1);
}
return newans.next;
}
}
LeetCode Add Two Numbers Problem Solution in Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carryover = 0
curr = None
while l1 or l2 or carryover:
if l1 and l2:
val_sum = l1.val + l2.val + carryover
digit = val_sum % 10
carryover = val_sum // 10
l1 = l1.next
l2 = l2.next
elif l1:
val_sum = l1.val + carryover
digit = val_sum % 10
carryover = val_sum // 10
l1 = l1.next
elif l2:
val_sum = l2.val + carryover
digit = val_sum % 10
carryover = val_sum // 10
l2 = l2.next
else:
digit = carryover
carryover = 0
if curr:
curr.next = ListNode(digit)
curr = curr.next
else:
curr = ListNode(digit)
head = curr
return head
0 Comments