Leetcode:445. Add Two Numbers II

这题可以结合着前面几个博客的思想来解决,当然网上给出了更好的解决方案值得学习

我自己实现的代码,因为对java指针的使用不太熟悉,调试了一个小时。思路:先将l1,l2存放到字符串中(因为字符串的长度不受限制,而数组的长度会受到限制),然后从数组的最后一位开始计算

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        ListNode result = new ListNode(-1);
        ListNode list = result;
        while (l1 != null) {
            sb1.append(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            sb2.append(l2.val);
            l2 = l2.next;
        }

        String str1 = sb1.toString();
        String str2 = sb2.toString();
        StringBuffer stringBuffer = new StringBuffer();
        int carry = 0;

        for (int i = str1.length() - 1, j = str2.length() - 1; i >= 0 || j >= 0
                || carry > 0; i--, j--) {
            int sum = 0;
            sum += (i >= 0) ? str1.charAt(i) - '0' : 0;
            sum += (j >= 0) ? str2.charAt(j) - '0' : 0;
            sum += carry;
            carry = sum / 10;
            sum = sum % 10;
            stringBuffer.append(sum);
        }
        System.out.println(stringBuffer.toString());
        for (int i = stringBuffer.toString().length() - 1; i >= 0; i--) {
            int a = stringBuffer.toString().charAt(i) - '0';
            list.next = new ListNode(a);
            list = list.next;
        }
        return result.next;
    }

网上的代码:https://discuss.leetcode.com/topic/65279/easy-o-n-java-solution-using-stack,最后几步指针没有看懂,使用stack也就是为了先计算靠右的数字,没有看懂的部分可可以用字符串来实现

原文地址:https://www.cnblogs.com/Michael2397/p/8029834.html