LeetCode算法学习(1)之两数相加

两数相加

LeetCode算法学习(1)之两数相加_第1张图片

 内置部分代码见:https://mp.csdn.net/postedit/81364767

       经过不断的尝试,终于满足了需求,但是当测试时使用的数据超过了Long的范围后报了如下的错误:

LeetCode算法学习(1)之两数相加_第2张图片

发现还是超出范围了,然后我想到了BigInteger,但是这不符合逻辑,我发现我是个死脑筋.....

这是我写的:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        long a = 0, b = 0, c = 0, count = 0;
        a = countListNode(l1);
        b = countListNode(l2);
        c = a + b;
        System.out.println(c);
        int d = String.valueOf(c).length();
        ListNode l3 = new ListNode(0);
        ListNode l = l3;
        for (int i = 0; i < d; i++) {
            l.val = (int) (c % 10);
            long x = (long) Math.pow(10, d - i - 1);
            long z = (c % x);
            c = c / 10;
            if (c>0) l.next = new ListNode((int) z);
            l = l.next;
        }
        return l3;
    }

    public long countListNode(ListNode l1) {
        long a = 0, count = 0;
        while (l1 != null) {
            a += l1.val * Math.pow(10, count);
            l1 = l1.next;
            count++;
        }
        return a;
    }
}

最后查看了别人写的,非常简洁,并且完全涉及不到数据类型的限制,学习了

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

简单,又明了,不过我的算法之路才刚开始,不急,加油!!

你可能感兴趣的:(算法学习)