兩數相加(力扣)

public class Test {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        System.out.println(l1);
        System.out.println(l2);
        System.out.println(test(l1, l2));
    }

    public static ListNode test(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode(0);
        ListNode cur = listNode;
        ListNode q = l1;
        ListNode p = l2;
        int carry = 0;
        while (q != null || p != null) {
            int x = (q != null) ? q.value : 0;
            int y = (p != null) ? p.value : 0;
            int sum = x + y + carry;
            carry = sum / 10;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            if (q != null) q = q.next;
            if (p != null) p = p.next;
        }
        if (carry > 0) {
            cur.next = new ListNode(carry);
        }
        return listNode.next;//listNode第一個數值爲0
    }

    static class ListNode {
        private ListNode next;
        private Integer value;

        public ListNode() {};

        public ListNode(int value) {
            this.value = value;
        }

        @Override
        public String toString() {
            StringBuilder s = new StringBuilder();
            ListNode listNode = this;
            s.append(listNode.value);
            while (listNode.next != null) {
                listNode = listNode.next;
                s.append(" -> ").append(listNode.value);
            }
            return s.toString();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章