Leikou question 2-add two numbers

Insert picture description here

At first, I looked down on this question a bit. I simply wanted to calculate the value expressed in this linked list first. For example, 2->4->3 means that 342
has never thought that the value expressed in this linked list may exceed the basic types int and long. Then add the two numbers after conversion to get the value 807, and then want to use the reverse method of StringBuilder to get 708, but the result is an out-of-bounds exception.

So the pit of this question:没有提示链表所表示的值可能超过基本类型


The solution of changing ideas

Since the linked list is a flashback, it means that the first node is the minimum value of this number, which can also be called the single digit. The
second node is the tens digit...
Then add each node in order to get a new one Linked list. It's just that each node of this linked list may exceed 9. That is to say, we need to advance one.
We find that 9+9 is 18, take 8 into 1, and even if the higher one gets 9+9=18, then 18+1=19 cannot get 20 anyway, that is, every A node can enter 1 at most,
then the remaining operation for each node, if the node val>=10, the next node val+=1, and the value of its own node needsval%=10

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
        ListNode l3 = l1, last = null;
        int c = 0, t1, t2;
        while (l1 != null || l2 != null) {
    
    
            if (l1 == null) {
    
    
                t1 = 0;
            } else {
    
    
                t1 = l1.val;
            }
            if (l2 == null) {
    
    
                t2 = 0;
            } else {
    
    
                t2 = l2.val;
            }
            ListNode tmp = new ListNode(t1 + t2);
            if (c == 0) {
    
    
                l3 = tmp;
                last = tmp;
                c++;
            } else {
    
    
                last.next = tmp;
                last = last.next;
            }
            if (l1 != null)
                l1 = l1.next;
            if (l2 != null)
                l2 = l2.next;
        }
        l1 = l3;
        while (l1 != null) {
    
    
            if (l1.val >= 10) {
    
    
                l1.val %= 10;
                if (l1.next == null) {
    
    // 特殊情况,例如124 456,高位4+6 >=10需要加一个节点
                    l1.next = new ListNode(1);
                    break;
                }
                l1.next.val += 1;
            }
            l1 = l1.next;
        }
        return l3;
    }

}

Unexpectedly, the efficiency is not bad, beating 99.92% of users.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41813208/article/details/109302898