美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: bin_guo | 来源:发表于2018-07-09 11:01 被阅读0次

Leetcode: 2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

My Final Solution:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null && l2 == null)
            return null;
        ListNode head = new ListNode(0);
        ListNode curr = head;
        int carry = 0;
        while(l1 != null || l2 != null){
            int sum = ((l1!=null)?l1.val:0) + ((l2!=null)?l2.val:0) + carry;
            curr.next = new ListNode(sum%10);
            carry = sum/10;
            l1 = (l1!=null)?l1.next:l1;
            l2 = (l2!=null)?l2.next:l2;
            curr = curr.next;
        }
        if(carry != 0){
            curr.next = new ListNode(carry);
        }
        return head.next;
    }
Referenced Solution:
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null && l2==null){
            return null;
        }
        ListNode head = new ListNode(0);
        ListNode point = head;
        int carry = 0;
        while(l1 != null && l2 != null){
            int sum = carry + l1.val + l2.val;
            point.next = new ListNode(sum%10);
            carry = sum/10;
            l1 = l1.next;
            l2 = l2.next;
            point = point.next;
        }
        while(l1 != null){
            int sum = carry + l1.val;
            point.next = new ListNode(sum%10);
            carry = sum/10;
            l1 = l1.next;
            point = point.next;
        }
        while(l2 != null){
            int sum = carry + l2.val;
            point.next = new ListNode(sum%10);
            carry = sum/10;
            l2 = l2.next;
            point = point.next;
        }
        if(carry != 0){
            point.next = new ListNode(carry);
        }
        return head.next;
    }
}

Referenced from
Author: Jack_sen
Link: https://blog.csdn.net/crazy1235/article/details/52914703

相关文章

网友评论

      本文标题:2. Add Two Numbers

      本文链接:https://www.haomeiwen.com/subject/hfuzuftx.html