Leetcode 之路 - 2. Add Two Numbers

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AnselLyy/article/details/80958449

2. Add Two Numbers

欢迎访问 我的个人博客

Description

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.

Thinking

  • 两个队列,看成是两个数字倒过来
  • 要求输出两个数字的和,并且按要求存放在队列中
  • 考虑按位加,判断和是否超过10,记录超过10的部分

Solution -1

  • 这个做法可能比较好理解一点,两个数存进两个list中,进行相加的工作
  • 如果一个的数字已经处理完,那就将另一个数字的剩余部分放进结果集中,这时应当考虑之前的和是否有超过10的部分没有处理完
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

    List<Integer> list1 = new LinkedList<>();
    List<Integer> list2 = new LinkedList<>();

    while (l1.next != null) {
        list1.add(l1.val);
        l1 = l1.next;
    }
    list1.add(l1.val);
    while (l2.next != null) {
        list2.add(l2.val);
        l2 = l2.next;
    }
    list2.add(l2.val);

    int maxLength = 0;
    int minLength = 0;
    List<Integer> result = new LinkedList<>();
    if (list1.size() >= list2.size()) {
        result = list1;
        maxLength = list1.size();
        minLength = list2.size();
    } else {
        result = list2;
        maxLength = list2.size();
        minLength = list1.size();
    }

    int carry = 0;
    int i;
    for (i = 0; i < minLength; i++) {
        int ans = list1.get(i) + list2.get(i) + carry;
        if (ans >= 10) {
            carry = ans / 10;
        } else {
            carry = 0;
        }
        result.set(i, ans % 10);
    }
    while (carry > 0 && i < maxLength) {
        int temp = result.get(i) + carry;
        carry = temp / 10;
        result.set(i, temp % 10);
        i++;
    }
    if (carry != 0) {
        result.add(carry);
    }

    ListNode answer = new ListNode(result.get(0));
    ListNode temp = answer;
    for (i = 1; i < result.size(); i++) {
        temp.next = new ListNode(result.get(i));
        temp = temp.next;
    }

    return answer;

}

Solution -2

  • 看到别人的做法,直接在 ListNode 上进行操作
  • 大体思路同我相同
  • 好处:减少了集合的使用,降低了复杂度
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

    ListNode head = new ListNode(-1);
    ListNode curr = head;
    int carry = 0;

    while (l1 != null || l2 != null) {
        int val1 = l1 != null ? l1.val : 0; // if null treat current val = 0
        int val2 = l2 != null ? l2.val : 0; // if null treat current val = 0
        int sum = val1 + val2 + carry;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        l1 = l1 != null ? l1.next : l1; 
        l2 = l2 != null ? l2.next : l2;
        carry = sum / 10;
    }

    if (carry != 0) {
        curr.next = new ListNode(carry);
    }

    return head.next;

}

猜你喜欢

转载自blog.csdn.net/AnselLyy/article/details/80958449
今日推荐