标签:
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
方法一:
标准链表操作,注意进位和当一个链表走完的情况。
注意最后一位如果有进位没有结算需要手动加1位。
def add_two_numbers(l1, l2) return l1 if l2.nil? return l2 if l1.nil? ans = ListNode.new(0) cur = ans temp = 0 while l1 and l2 cur.next = ListNode.new((l1.val + l2.val + temp) % 10) temp = (l1.val + l2.val + temp) / 10 l1 = l1.next l2 = l2.next cur = cur.next end while l1 cur.next = ListNode.new((l1.val + temp)%10) temp = (l1.val + temp) / 10 l1 = l1.next cur = cur.next end while l2 cur.next = ListNode.new((l2.val + temp)%10) temp = (l2.val + temp) / 10 l2 = l2.next cur = cur.next end cur.next = ListNode.new(temp%10) if temp > 0 ans.next end
方法二:
Python、Ruby不会溢出,可以转换成数字相加后再转回链表。
def add_two_numbers(l1, l2) return l1 if l2.nil? return l2 if l1.nil? s1 = Array.new s2 = Array.new n = Array.new while l1 s1.unshift(l1.val) l1 = l1.next end while l2 s2.unshift(l2.val) l2 = l2.next end x = s1.join.to_i+s2.join.to_i n = x.to_s.chars.map(&:to_i) ans = ListNode.new(0) d = ans n.length.times do d.next = ListNode.new(n.pop) d = d.next end ans.next end
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4569274.html