这题很直白,就是把两个数相加。注意一下进位的问题就可以啦。
啊呀,最喜欢这种brute force的题了(就是这么不求上进)。
今天就没什么要讲的了╮(╯-╰)╭ 最后贴个代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode p = head; int carry = 0; int sum = 0; for(; l1!=null && l2!=null; l1=l1.next, l2=l2.next){ sum = l1.val + l2.val + carry; carry = sum/10; ListNode q = new ListNode(sum%10); p.next = q; p = p.next; } while(l1!=null){ sum = l1.val + carry; carry = sum/10; ListNode q = new ListNode(sum%10); p.next = q; p = p.next; l1 = l1.next; } while(l2!=null){ sum = l2.val + carry; carry = sum/10; ListNode q = new ListNode(sum%10); p.next = q; p = p.next; l2 = l2.next; } if(carry != 0){ ListNode q = new ListNode(1); p.next = q; p = p.next; } return head.next; } }
|