美文网首页
Add Tow Numbers

Add Tow Numbers

作者: EIP_Miracle | 来源:发表于2017-10-21 23:30 被阅读0次

    Description:

    You are give two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.

    You may assume the two numbers do not contain leading zero, except the number 0 itself.

    思路:

    因为两个数字都是倒序储存的,所以直接送链表的开头逐个相加即可,但是需要注意的是,当整个循环结束后,可能进位不是0,所以要把进位加到结果中去,这是一个比较重要的临界条件。

    Solution:

    public static ListNode add_tow_numbers(ListNode l1, ListNode l2){
      ListNode head = new ListNode(0);
      ListNode cur = head;
      int carry = 0;
      while(l1 != null || l2 != null){
        int x = (l1 != null) ? l1.val : 0;  //缺少的位用零补上
        int y = (l2 != null) ? l2.val : 0;
        int sum = x + y + carry;
        carry = sum / 10;
        cur.next = new ListNode(sum %= 10);
        cur = cur.next;
        if(l1 != null) l1 = l1.next;  //先判断是不是null,否则可能出现NullPointerException
        if(l2 != null) l2 = l2.next;
      }
      if(carry != 0){   //如果还有进位就加到结果的最后
        cur.next = new ListNode(carry);
      }
      return head.next;
    }
    

    相关文章

      网友评论

          本文标题:Add Tow Numbers

          本文链接:https://www.haomeiwen.com/subject/qlbwuxtx.html