leetcode -- 2. Add Two Numbers
阿新 • • 發佈:2018-12-19
問題描述
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
AC程式碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tmp = new ListNode(0);
ListNode head = tmp;
int carry = 0;
int val = 0;
while(l1 != null || l2 != null){ //即使 l1 和 l2 長度不一致也適用,極大地減少了程式碼量
if(l1 == null) l1 = new ListNode(0); // 如果 l1 已經遍歷完了,l1 的下一個節點用 0 代替
if(l2 == null) l2 = new ListNode(0); //同理
val = l1.val + l2.val + carry; // 別忘了加進位
carry = val / 10;
tmp.next = new ListNode(val % 10);
tmp = tmp.next;
l1 = l1.next;
l2 = l2.next;
}
if(carry != 0) tmp.next = new ListNode(carry); //別忘記了:最後如果有進位的話,要把進位加上
return head.next;
}
}