题解报告LeetCode#2:两数相加

题意:LeetCode#2:两数相加

思路:

代码:

  1. class Solution {
  2. public ListNode addTwoNumbers(ListNode l1, ListNodel2) {
  3. ListNode pre = new ListNode(0);
  4. ListNode cur = pre;
  5. int carry = 0;
  6. int x, y, sum;
  7. while (l1 != null || l2 != null) {
  8. x = l1 == null ? 0 : l1.val;
  9. y = l2 == null ? 0 : l2.val;
  10. sum = x + y + carry;
  11. carry = sum / 10;
  12. sum = sum % 10;
  13. cur.next = new ListNode(sum);
  14. cur = cur.next;
  15. if (l1 != null)
  16. l1 = l1.next;
  17. if (l2 != null)
  18. l2 = l2.next;
  19. }
  20. if (carry == 1) {
  21. cur.next = new ListNode(carry);
  22. }
  23. return pre.next;
  24. }
  25. }

题解报告LeetCode#445:两数相加Ⅱ

题意:LeetCode#445:两数相加Ⅱ

思路:利用辅助栈

代码:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();

        while (l1 != null) {
            stack1.push(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            stack2.push(l2.val);
            l2 = l2.next;
        }

        int carry = 0;
        ListNode head = null;
        while (!stack.isEmpty() || !stack.isEmpty() || carry != 0) {
            int sum = carry;
            sum += stack1.isEmpty() ? 0 : stack1.pop();
            sum += stack2.isEmpty() ? 0 : stack2.pop();
            ListNode node = new ListNode(sum % 10);
            node.next = head;
            head = node;
            carry = sum / 10;
        }

        return head;
    }
}