[Force] 2. buckle two numbers together

First, the subject description:

We are given two non-empty list is used to represent two non-negative integer. Where their respective bits are stored in reverse order of the way, and they each node can store only one digit.
If we add up these two numbers, it will return a new list and to represent them.
You can assume that in addition to the numbers 0, these two numbers will not begin with 0.

Example:

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

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/add-two-numbers
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Second, the problem-solving ideas:

1, first determine whether the list l1 and l2 are empty, if are empty or null.
2, and even create a new list, and will be placed in a new list of two numbers of nodes. Traverse the list until it is empty l1, l2 is empty and carry carry zero.
3, it is necessary to consider different chain lengths l1 and l2, whether a carry bit carry.

Third, Code Description:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      if(l1==null&&l2==null){
          return null;
      }
      //carry表示进位数
      int carry=0;  
      //创建新链表
      ListNode newHead=new ListNode(-1);
      ListNode newTail=newHead;
      while(l1!=null||l2!=null||carry!=0){
          if(l1!=null){
            carry+=l1.val;
            l1=l1.next;
          }
          if(l2!=null){
            carry+=l2.val;
            l2=l2.next;
          }
          //新节点的值为%10后的余数
          newTail.next=new ListNode(carry%10);
          newTail=newTail.next;
          //标志位为/10后的整数       
          carry/=10;
      }
      return newHead.next;
    }
}
Published 75 original articles · won praise 14 · views 1896

Guess you like

Origin blog.csdn.net/qq_45328505/article/details/104720283