标签:
#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 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): number1 = 0 len1 = 0 number2 = 0 len2 = 0 while l1 != None: number1 = number1 + l1.val*10**len1 l1 = l1.next len1 = len1 + 1 while l2 != None: number2 = number2 + l2.val*10**(len2) l2 = l2.next len2 = len2 + 1 sumNumber = number1 + number2 head = None indexNode = None first = True if sumNumber >= 0 and sumNumber <= 9: head = ListNode(sumNumber) else: while sumNumber: yushu = sumNumber % 10 l3 = ListNode(yushu) if first: head = l3 indexNode = head first= False else: indexNode.next = l3 indexNode = indexNode.next sumNumber = sumNumber//10 return head
标签:
原文地址:http://my.oschina.net/stevenKelly/blog/381846