LeetCode-兩數相加
阿新 • • 發佈:2019-02-03
給定兩個非空連結串列來表示兩個非負整數。位數按照逆序方式儲存,它們的每個節點只儲存單個數字。將兩數相加返回一個新的連結串列。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { boolean carry =false; ListNode result =new ListNode(); ListNode temp =result; int sum=0; while(l1!=null||l2!=null||carry) { if(null!=l1) { sum = l1.getValue(); l1=l1.getNext(); } if(null!=l2) { sum+=l2.getValue(); l2=l2.getNext(); } if(carry) { sum+=1; carry=false; } if(sum>10) { carry=true; sum-=10; } temp.setValue(sum); ListNode next = new ListNode(); temp.setNext(next); temp =next; sum=0; } return result; } } class ListNode { private int value; private ListNode next; public void setNext(ListNode next) { this.next = next; } public ListNode getNext() { return next; } public void setValue(int value) { this.value = value; } public int getValue() { return value; } }
標準答案:
class Solution{ public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode tmp = null; ListNode result = null; int carry = 0; while (l1 != null || l2 != null || carry != 0) { int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; carry = sum / 10; ListNode node = new ListNode(sum % 10); if (tmp == null) { tmp = node; result = tmp; } else { tmp.next = node; tmp = tmp.next; } l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; } return result; } }