美文网首页
leedcode:Add Two Numbers

leedcode:Add Two Numbers

作者: firststep | 来源:发表于2019-02-27 19:52 被阅读0次

问题: 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 contain 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.

解答:

public class Leedcode2 {
    public static void main(String args[]) {
        Leedcode2 leedcode2 = new Leedcode2();
        ListNode l1= new ListNode(2);
        ListNode l2= new ListNode(3);
        ListNode l3= new ListNode(6);
        l1.next = l2;
        l2.next = l3;
        ListNode l4= new ListNode(2);
        ListNode l5= new ListNode(7);
        ListNode l6= new ListNode(6);
        l4.next = l5;
        l5.next = l6;
        ListNode result =leedcode2.addTwoNumbers(l1,l4);
        while (result !=null) {
            System.out.println(result.val);
            result = result.next;
        }

    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode((l1.val+l2.val)%10);
        ListNode temp = l3;
        int f = (l1.val + l2.val)>=10 ? 1 : 0;
        l1 = l1.next;
        l2 = l2.next;
        while (l1 !=null || l2!=null || f!=0) {
            int val1 = 0;
            int val2 = 0;
            if (l1!=null) {
                val1 = l1.val;
                l1 = l1.next;
            }
            if (l2!=null) {
                val2 = l2.val;
                l2 = l2.next;
            }
            int sum = (val1+val2+f)>=10 ? (val1+val2+f)%10:(val1+val2+f);
            f= (val1+val2+f)>=10 ? 1:0;
            temp.next = new ListNode(sum);
            temp = temp.next;
        }
        return l3;
    }
}

首先拿到这道题第一反应就应该考虑到肯定会用到迭代,然后慢慢捋一下思路编写代码。

相关文章

网友评论

      本文标题:leedcode:Add Two Numbers

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