【注意事項】アルゴリズム一般質問01

1. 自分で書いた貧弱なコード

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head=new ListNode();
        ListNode p=head;
        int target=0;
        do{
            l1=l1==null?new ListNode(0):l1;
            l2=l2==null?new ListNode(0):l2;
            int num=l1.val+l2.val;//两数和
            p.val=num%10+target;//现在值
            target=0;
            if (num>=10) target=1;//两数相加是否大于十
            if(p.val>=10){//相加数0+9,有进位1的情况
                target+=1;
                p.val%=10;
            }
            /**链表往下移*/
            if(l1.next!=null||l2.next!=null) {
                p.next = new ListNode();
                p = p.next;
            }
            l1=l1.next;
            l2=l2.next;
        }
        while(l1!=null||l2!=null);

        if (target>0){
            p.next=new ListNode(1);
        }
        return head;
    }

2. 公式コード

 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
          ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }

 コードを公式 Web サイトにプッシュできるように頑張ってください。

おすすめ

転載: blog.csdn.net/m0_56233309/article/details/131104722