Number two] [01 LeetCode learning record sum (Java implementation)

2. The two numbers together (Java implementation)

Title : given two non-empty list is used to represent two non-negative integer. Among them, in accordance with their respective median is the reverse of the way storage, 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.

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

Refresh the idea after seeing bigwigs Code

Ideas:

  • The two lists are the same as the length of the traversal, if a list is shorter at the front fill 0, eg: 987 + 23 = 987 + 023 = 1010
  • At the same time every computing need to consider the issue on a carry, but also need to update the current value after the end of the carry-bit computing
  • If the two lists all of the traversal is complete, the carry value is 1, at the forefront of the list to add the new node 1. Here to explain, because you end result is based on the list bit by bit to return, so regardless of the middle how much you carry, these carry you added to the list in the calculation until the last one if there is a carry, then we would new insert a node (val = 1).
  • The last structure returned results list. That white is the list operating in Java, this step must be a deep understanding of the problem: reference Java objects in the object . If that is not clear, see objects and references Talking in Java . In simple terms, we first create a header object, two references head, temp point to the head. Next, head does not move, temp people as a tool to link the new object (node) (= the newNode temp.next;) , then the tail of the linked list node points * (temp = temp.next;) * . head point list head has been used to return results. ( Note: Since the head node is not a part of the result, it returns head.next )
/**
 * 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) {
        //创建一个头结点对象
        ListNode head = new ListNode(0);
        //两个引用head和temp都指向这个对象,head用来指向链表头,temp是工具人(有点像C语言中移动的指针)
        ListNode temp = head;
        //进位标志carry
        int carry = 0;
        //每一位的求和sum
        int sum =0;
        while(l1!=null||l2!=null){
            int x = null==l1?0:l1.val;
            int y = null==l2?0:l2.val;
            sum = x+y+carry;
            //计算本位是否有进位
            carry = sum/10;  
            //插入本位的计算结果
            ListNode newNode = new ListNode(sum%10);
            //将新结点插入到链表中
            temp.next=newNode;
            //指针移动,temp一直指向链表的尾部
            temp = temp.next;
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
        }
        //最高位如果有进位,则插入一个新结点(val=1)
        if(carry>0){
            temp.next = new ListNode(carry);
        }
        //head指向的头结点不是结果的一部分,真正的返回结果从head.next开始
        return head.next;
       
    }
}
  • result:
    Here Insert Picture Description
  • I believe many people like me watching head.next feel very unhappy, why should a useless head node, I want my list is the result, not again remove a head node. So I will modify the above code a little bit to solve the above problems, it is actually very simple, add a judge on the line.
/**
 * 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) {
        ListNode head = null;
        ListNode temp = null;
        //进位标志carry
        int carry = 0;
        //每一位的求和sum
        int sum =0;
        while(l1!=null||l2!=null){
            int x = null==l1?0:l1.val;
            int y = null==l2?0:l2.val;
            sum = x+y+carry;
            //计算本位是否有进位
            carry = sum/10;  
            //插入本位的计算结果
            ListNode newNode = new ListNode(sum%10);
            //将新结点插入到链表中
            //如果头结点为null,就将head指向新创建的结点
            if(head==null){
                head = newNode;
                temp = head;
            }else{
                temp.next=newNode;
                temp = temp.next;

            }
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
        }
        //最高位如果有进位,则插入一个新结点(val=1)
        if(carry>0){
            temp.next = new ListNode(carry);
        }
        //head指向的头结点不是结果的一部分,真正的返回结果从head.next开始
        return head.next;
       
    }
}
  • result:
    Here Insert Picture Description

The idea of ​​my own immaturity of the next record

See this topic, I first thought is, to put the two lists l1 and l2 input into integer, obtained by adding the results, then the results returned into the list. (So stupid ways you can tell the algorithm level ... usually do not work hard, coding only sad ... so be good to knock the code ah!)

/**
 * 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) {
        StringBuilder str1 = new StringBuilder();
        StringBuilder str2 = new StringBuilder();
       //遍历l1链表,存储到str1中
        while(l1!=null){
        str1.append(l1.val);
        l1=l1.next;
        }
        //遍历l2链表,存储到str2中
        while(l2!=null){
            str2.append(l2.val);
            l2=l2.next;
        }
       
        try{
            //将l1、l2中字符串逆序后准成int类型
            int r1 = Integer.parseInt(str1.reverse().toString());
            int r2 = Integer.parseInt(str2.reverse().toString());
            //求和得到结果
            int r = r1+r2;
            // System.out.println(r1+" + "+r2+"="+" "+r);
            //将结果r从低位到高位插入到结果链表中
            ListNode head = null;
            if(r==0){
                return new ListNode(0);
            }
            while(r!=0){
                ListNode newNode = new ListNode(r%10);
                if(head ==null) {
                    head = newNode; 
                }else {
                    ListNode tmp = head;
                    while(tmp.next!=null) {
                        tmp = tmp.next;
                    }
                    tmp.next = newNode;
                }
                r = r/10;
            }
             return head;
        }catch(Exception e){
        }    
     return null;
    }
}


  • Results:
    Here Insert Picture Description
    there is a problem: with the calculation result stored int type, but the value is much larger than the test range of the int type can be represented. I read some posts said long does not work, use BigDecimal through.
Released three original articles · won praise 2 · views 34

Guess you like

Origin blog.csdn.net/qq_39754086/article/details/104817461