Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

两数相加 #43

Open
louzhedong opened this issue Aug 31, 2018 · 0 comments
Open

两数相加 #43

louzhedong opened this issue Aug 31, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第2题

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

思路

简单的链表,每相加两个链表的值,将进位放存放在carry里,余数存放在remainder里。进行下一次计算时,需要加上carry的值。另一个易错点就是当其中一个链表已经到尾部,而carry的值为1时的情况。

解答

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
  var result = new ListNode(0);
  var head = result;
  var carry = 0;
  var remainder = 0;
  while (l1 != null && l2 != null) {
    var temp = l1.val + l2.val + (carry ? 1 : 0);
    if (temp >= 10) {
      carry = 1;
      remainder = temp % 10;
    } else {
      carry = 0;
      remainder = temp;
    }
    var add = new ListNode(remainder);
    result.next = add;
    result = result.next;
    l1 = l1.next;
    l2 = l2.next;
  }
  if (l1 == null && l2 == null) {

  }
  if (l1 == null) {
    while (l2 != null) {
      if (carry) {
        var temp = l2.val + (carry ? 1 : 0);
        if (temp >= 10) {
          carry = 1;
          remainder = temp % 10;
        } else {
          carry = 0;
          remainder = temp;
        }
        var add = new ListNode(remainder);
        result.next = add;
        result = result.next;
        l2 = l2.next;
      } else {
        var add = new ListNode(l2.val);
        result.next = add;
        result = result.next;
        l2 = l2.next;
      }
    }
  } else {
    while (l1 != null) {
      if (carry) {
        var temp = l1.val + (carry ? 1 : 0);
        if (temp >= 10) {
          carry = 1;
          remainder = temp % 10;
        } else {
          carry = 0;
          remainder = temp;
        }
        var add = new ListNode(remainder);
        result.next = add;
        result = result.next;
        l1 = l1.next;
      } else {
        var add = new ListNode(l1.val);
        result.next = add;
        result = result.next;
        l1 = l1.next;
      }
    }
  }
  if (carry) {
    var add = new ListNode(1);
    result.next = add;
    result = result.next;
    carry = 0;
  }
  return head.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant