LeetCode - 2 - Add Two Numbers
阿新 • • 發佈:2017-06-10
dtw ble bind ber plus binding bsp pan number
題目
URL:https://leetcode.com/problems/add-two-numbers/
解法
沒什麽特殊的解法,按位相加即可。
註意點:
1、l1 和 l2 不一樣長。
2、最終的進位。
單層循環,時間復雜度O(max(l1.length, l2.length)),運行時間約為 50 ms。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode l3 = new ListNode(-1); ListNode tl3 = l3; int plus = 0;while (l1 != null || l2 != null || plus == 1) { int value = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + plus; if (value >= 10) { plus = 1; value -= 10; } else { plus = 0; } ListNode next= new ListNode(value); tl3.next = next; tl3 = tl3.next; if (l1 != null) l1 = l1.next; if (l2 != null) l2 = l2.next; } return l3.next; }
總結
膽大心細。無論是美女還是題目,你都可以得手。
LeetCode - 2 - Add Two Numbers