题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
         if (head1 == null) return head2;
        if (head2 == null) return head1;
        StringBuilder builder1 = new StringBuilder();
        StringBuilder builder2 = new StringBuilder();
        while (head1!=null) {
            builder1.append(head1.val);
            //num1 = num1*10 + head1.val;
            head1 = head1.next;
        }
        while (head2!=null) {
            builder2.append(head2.val);
            //num2 = num2*10 + head2.val;
            head2 = head2.next;
        }

        int value = builder1.charAt(builder1.length()-1) + builder2.charAt(builder2.length()-1) - 96;
        ListNode head = new ListNode(value%10);
        int jin = value/10;
        for (int i = 1; i < builder1.length()||i<builder2.length(); i++) {
             if (i>builder1.length()-1) {
                 value = builder2.charAt(builder2.length() - 1 - i)-48 + jin;
                 ListNode listNode = new ListNode(value%10);
                 listNode.next = head;
                 head = listNode;
                 jin = value/10;
             } else if (i>builder2.length()-1) {
                 value = builder1.charAt(builder1.length() - 1 - i)-48 + jin;
                 ListNode listNode = new ListNode(value%10);
                 listNode.next = head;
                 head = listNode;
                 jin = value/10;
             } else {
                 value = (builder1.charAt(builder1.length()-1-i) + builder2.charAt(builder2.length()-1-i) - 96 + jin);
                 ListNode listNode = new ListNode(value%10);
                 jin = value/10;
                 listNode.next = head;
                 head = listNode;
             }
        }
        if (jin>0) {
            ListNode listNode = new ListNode(jin);
            listNode.next = head;
            head = listNode;
        }
        return head;
    }
}

全部评论

相关推荐

10-15 16:27
门头沟学院 C++
LeoMoon:建议问一下是不是你给他付钱😅😅
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务