Leetcode第二題解題java實現
阿新 • • 發佈:2019-01-10
問題:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
審題:
該題把數字按位拆開以倒序方式存放在一個連結串列中,要求計算兩個數字的和,以同樣的方式返回。該題的考察點是連結串列的遍歷,他以倒序儲存數字,減低了解題的繁瑣程度,想象一下,分別從兩個連結串列中同時取出一個數,比如第一個,這兩數都是個位上的數,直接相加即可,得到的數看是否有進位,把進位值記下。
我的想法是把兩個連結串列的數挨個遍歷取出,沒取出一位數就相加再加進位,並對10求餘,存到另外一個連結串列的節點中,取整得到進位,存起來,
一直迴圈到兩連結串列為空。
解題:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null)
{
return null;
}
ListNode lhead;
ListNode l = new ListNode(0);
lhead = l;
int flag=0;
while(l1!=null || l2!=null)
{
ListNode lnext = new ListNode(0);
int a = l1==null?0:l1.val;
int b = l2==null?0:l2.val;
lnext.val = (a+b+flag)%10 ;
flag = (a+b+flag)/10;
l.next = lnext;
l = l.next;
l1 = l1==null?null:l1.next;
l2 = l2==null?null:l2.next;
}
if(flag != 0) //如果還有進位,新增節點存入其中
{
ListNode lnext = new ListNode(0);
lnext.val = flag;
l.next = lnext;
}
return lhead.next;
}
}
該解題思維相對正常,是靠生活計算經驗解題,沒有複雜演算法,排名居中。