Skip to content

Commit

Permalink
Added 302 - Leetcode
Browse files Browse the repository at this point in the history
Added 302 - Leetcode - 0002 Add Two Numbers
Changed directory name from 301 to 301 - Witch Jobsite
  • Loading branch information
diegomendez40 committed Feb 10, 2024
1 parent dfa5056 commit f0925ed
Show file tree
Hide file tree
Showing 15 changed files with 39 additions and 0 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
39 changes: 39 additions & 0 deletions 302 - Leetcode/0002 Add Two Numbers/AddTwoNumbers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* 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) {

ListNode prePreFirstResult = new ListNode();
prePreFirstResult.next = new ListNode();
ListNode result = prePreFirstResult.next;
int carry = 0;
// While a new node is necessary...
while (carry == 1 || l1 != null || l2 != null){
if (l1 == null){
l1 = new ListNode(0);
}
if (l2 == null){
l2 = new ListNode(0);
}
ListNode nextResult = new ListNode ((l1.val + l2.val + carry)%10);
result.next = nextResult;
if (l1.val + l2.val + carry >= 10){
carry = 1;
} else {
carry = 0;
}
l1 = l1.next;
l2 = l2.next;
result = nextResult;
}
return prePreFirstResult.next.next;
}
}

0 comments on commit f0925ed

Please sign in to comment.