当前位置 博文首页 > 无限迭代中......:LeetCode 2 两数相加

    无限迭代中......:LeetCode 2 两数相加

    作者:[db:作者] 时间:2021-07-19 16:24

    https://leetcode-cn.com/problems/add-two-numbers/
    在这里插入图片描述

    解决方案

    /**
     * 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) {
            int sum = 0;
            ListNode head = l1;
            while (l1 != null) {            
                if (l2 != null) {
                    sum = l1.val + l2.val;
                    l2 = l2.next;
                    if(l1.next == null ){
                        l1.next = l2;
                        l2 = null;
                    }
                }else{
                    sum = l1.val;
                    if(sum / 10 ==0){
                        break;
                    }
                }
                l1.val = sum % 10;
                if( sum / 10>0){
                    if(l1.next==null){
                        l1.next = new ListNode(sum/10);
                        break;
                    }else{
                        l1.next.val = l1.next.val + sum / 10;
                    }
                }
                l1 = l1.next;
            }
            return head;
        }
    }
    

    参考文章

    cs
    下一篇:没有了