LeetCode演算法2:java 兩數相加
阿新 • • 發佈:2018-12-23
問題:
給出兩個 非空 的連結串列用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式儲存的,並且它們的每個節點只能儲存 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的連結串列來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
解答:
思路:問題不難,就是注意採用列表求加法,判斷進位。這裡對判斷時進行了一個連續或運算的技巧。
public class _02AddTwoNumbers{ 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; if (l1!=null) l1 = l1.next; if (l2!=null) l2 = l2.next; }else{ tmp.next = node; tmp = tmp.next; if (l1!=null) l1 = l1.next; if (l2!=null) l2 = l2.next; } } return result; } public static void main(String[] args){ _02AddTwoNumbers addtwonumbers = new _02AddTwoNumbers(); ListNode tmp = null; ListNode l1 = new ListNode(1); tmp = new ListNode(2); l1.next = tmp; tmp.next = new ListNode(3); tmp = tmp.next; tmp.next = new ListNode(4); tmp = tmp.next; System.out.println("###########l1###########"); addtwonumbers.getListlength(l1); addtwonumbers.readList(l1); ListNode l2 = new ListNode(1); tmp = new ListNode(0); l2.next = tmp; tmp.next = new ListNode(8); tmp = tmp.next; tmp.next = new ListNode(9); tmp = tmp.next; tmp.next = new ListNode(1); tmp = tmp.next; System.out.println("###########l2###########"); addtwonumbers.readList(l2); addtwonumbers.getListlength(l2); ListNode result = addtwonumbers.addTwoNumbers(l1,l2); System.out.println("###########result###########"); addtwonumbers.readList(result); addtwonumbers.getListlength(result); } public void readList(ListNode list){ System.out.println("the list is:"); if (list == null) return; while(list !=null){ System.out.print(list.val+","); list = list.next; } } public void getListlength(ListNode list){ System.out.println("the list length is:"); int i = 0; if (list == null) System.out.println("list length is "+i); while(list !=null){ i++; list = list.next; } System.out.println("list length is "+i); } } class ListNode{ int val; ListNode next; ListNode(int x){ val = x; } }