Two numbers sum (list)

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:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Cause: 342 + 465 = 807
Analysis: when added in reverse order addition, the head node point addition operation is started
Here Insert Picture Description
digital sum may overflow, it is necessary to introduce into bits, starting from the header added down through to the end of the list. Remember to update the position of each bit value of the feed and mobile nodes.
Code:

public class ListNode {
     int value;
      ListNode next;
      ListNode(int x) { value = x; }
  class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int jinwei = 0;  //进位
            int x = 0, y = 0;
            ListNode tempHead = new ListNode(0);  //哑元结点
            ListNode p1 = l1;
            ListNode p2 = l2;
            ListNode currency = tempHead;
            while (p1 != null || p2 != null) {
                if (p1 != null) {
                    x = p1.value;
                } else {
                    x = 0;
                }
                if (p2 != null) {
                    y = p2.value;
                } else {
                    y = 0;
                }
                int result = jinwei + x + y;
                jinwei = result / 10;   //更新进位的值
                currency.next = new ListNode(result % 10);    //新节点(当前的下一个)
                currency=currency.next;
                if (p1 != null) {           //同时往后走
                    p1 = p1.next;
                }
                if (p2 != null) {
                    p2 = p2.next;
                }
            }

            if(jinwei>0){
                currency.next=new ListNode(jinwei);
            }
            return tempHead.next;
        }
    }

Daily practice, encourage each other.

Guess you like

Origin blog.csdn.net/weixin_42373873/article/details/90291420