LinkedList Add Two Numbers: LeetCode

We Are Going To Discuss About LinkedList Add Two Numbers: LeetCode. So lets Start this Java Article.

LinkedList Add Two Numbers: LeetCode

Advertisements
  1. LinkedList Add Two Numbers: LeetCode

    I like your solution but you have bit incomplete logic.
    class Solution { //ListNode head; public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int x = 0; int y = 0; int z = 1; while(l1 != null){ x += z*l1.val; z*=10; l1 = l1.next; }

  2. LinkedList Add Two Numbers: LeetCode

    I like your solution but you have bit incomplete logic.
    class Solution { //ListNode head; public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int x = 0; int y = 0; int z = 1; while(l1 != null){ x += z*l1.val; z*=10; l1 = l1.next; }

Solution 1

Advertisements

I like your solution but you have bit incomplete logic.

class Solution {
    //ListNode head;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int x = 0;
        int y = 0;
        int z = 1;

        while(l1 != null){
            x += z*l1.val;
            z*=10;
            l1 = l1.next;
        }

        z = 1;
        while(l2 != null){
            y += z*l2.val;
            z*=10;
            l2 = l2.next;
        }

        int sum = x + y;
        if (sum == 0) {
            return new ListNode(0);
        }

        ListNode node = null, head = null;
        while(sum > 0){
            int digit = sum % 10;
            ListNode n = new ListNode(digit);
            if (node == null) {
                head = node = n;
            } else {
                node.next = n;
                node = node.next;
            }
            
            sum = sum / 10;
        }

        return head;
    }
}

I just changed one or two things after int sum = x + y;

Original Author Of This Content

Conclusion

Advertisements

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Advertisements
Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment