(牛客)鏈式A+B

題目來源

鏈式A+B

題目描述

有兩個用鏈表表示的整數,每個結點包含一個數位。這些數位是反向存放的,也就是個位排在鏈表的首部。編寫函數對這兩個整數求和,並用鏈表形式返回結果。

給定兩個鏈表ListNode* A,ListNode* B,請返回A+B的結果(ListNode*)。

題目解析

將鏈表轉換爲整數,進行求和計算,然後將整數又轉換爲鏈表即可

題目解答

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Plus {
    public ListNode plusAB(ListNode a, ListNode b) {
        //將鏈表轉換爲整數
        int aValue=listNodeConvertIntValue(a);
        int bVlaue=listNodeConvertIntValue(b);
        //計算求和
        int sumValue=aValue+bVlaue;
        //將整數轉換爲鏈表
        return intValueConvertListNode(sumValue);
    }
    private int listNodeConvertIntValue(ListNode node){
        StringBuilder sb=new StringBuilder();
        ListNode cur=node;
        while(cur!=null){
            sb.append(cur.val);
            cur=cur.next;
        }
        return Integer.parseInt(sb.reverse().toString());
    }
    private ListNode intValueConvertListNode(int value){
        char[] ch=String.valueOf(value).toCharArray();
        ListNode node=new ListNode(Integer.parseInt(String.valueOf(ch[ch.length-1])));
        ListNode cur=node;
        //整數反轉存儲到鏈表中
        for(int i=ch.length-2;i>=0;i--){
            ListNode newNode=new ListNode(Integer.parseInt(String.valueOf(ch[i])));
            cur.next=newNode;
            cur=newNode;
        }
        return node;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章