#2 Add Two Numbers 兩數之和

JourneyNg
Nov 16, 2020

just for the record, not the best solutions.

if you like to study together, my discord: Journey#9805

package com.journey;


public class AddTwoNumbers_兩數相加_002 {
//solution
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;//進位

while (l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val; //如果null就補0
int y = l2 == null ? 0 : l2.val; //如果null就補0
int sum = x + y + carry;

carry = sum / 10; //看是有要進位
sum = sum % 10; //得出個位數
cur.next = new ListNode(sum); //cur.next = 0.next = 指向個位數(sum)
cur = cur.next; //個位數的next = 十位數

if (l1 != null) { //如果還有,指向下一位
l1 = l1.next;
}
if (l2 != null) { //如果還有,指向下一位
l2 = l2.next;
}
}

//退出循环
if (carry == 1) { //最后如果有進位,新增node
cur.next = new ListNode(carry);
}
return pre.next;
}


//test
public static void main(String[] args) {
ListNode node1 = new ListNode(7, new ListNode(8, new ListNode(9)));
ListNode node2 = new ListNode(2, new ListNode(3, new ListNode()));
ListNode answer = addTwoNumbers(node1, node2);
System.out.println(answer.val);
System.out.println(answer.next.val);
System.out.println(answer.next.next.val);
System.out.println(answer.next.next.next.val);
}
}


//constructor
class ListNode {
int val;
ListNode next;

ListNode() {
}

ListNode(int val) {
this.val = val;
}

ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}

}

--

--