Advertisement
exmkg

Untitled

Sep 23rd, 2024
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     int val;
  5.  *     ListNode next;
  6.  *     ListNode() {}
  7.  *     ListNode(int val) { this.val = val; }
  8.  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9.  * }
  10.  */
  11. class Solution {
  12.     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  13.         ListNode dummy = new ListNode(0); // creating an dummy list
  14.         ListNode curr = dummy; // intialising an pointer
  15.         int carry = 0; // intialising our carry with 0 intiall
  16.         // while loop will run, until l1 OR l2 not reaches null OR if they both reaches null. But our carry has some value in it.
  17.         // We will add that as well into our list
  18.         while(l1 != null || l2 != null || carry == 1){
  19.             int sum = 0; // intialising our sum
  20.             if(l1 != null){ // adding l1 to our sum & moving l1
  21.                 sum += l1.val;
  22.                 l1 = l1.next;
  23.             }
  24.             if(l2 != null){ // adding l2 to our sum & moving l2
  25.                 sum += l2.val;
  26.                 l2 = l2.next;
  27.             }
  28.             sum += carry; // if we have carry then add it into our sum
  29.             carry = sum/10; // if we get carry, then divide it by 10 to get the carry
  30.             ListNode node = new ListNode(sum % 10); // the value we'll get by moduloing it, will become as new node so. add it to our list
  31.             curr.next = node; // curr will point to that new node if we get
  32.             curr = curr.next; // update the current every time
  33.         }
  34.         return dummy.next; // return dummy.next bcz, we don't want the value we have consider in it intially!!
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement