[算法题] Add Two Numbers
生活随笔
收集整理的這篇文章主要介紹了
[算法题] Add Two Numbers
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目內容
題目來源:LeetCode
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
題目思路
這個題目是倒序存儲了兩個數字,然后模擬進行加法運算。
本題中需要學習到的知識有:
1. 分別使用/和%來代表進位符號flag和當前位的值value
2. 成立啞結點(頭結點),這樣可以方便很多。
Python代碼
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = Noneclass Solution(object):def addTwoNumbers(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""if not l1 and not l2:returnif not l1:return l2if not l2:return l1dummy=ListNode(-1)p=dummyflag=0while l1 and l2:value=(l1.val+l2.val+flag)%10p.next=ListNode(value)p=p.nextflag=(l1.val+l2.val+flag)/10l1=l1.nextl2=l2.nextwhile l1:value=(l1.val+flag)%10p.next=ListNode(value)p=p.nextflag=(l1.val+flag)/10l1=l1.nextwhile l2:value=(l2.val+flag)%10p.next=ListNode(value)p=p.nextflag=(l2.val+flag)/10l2=l2.nextif flag>0:p.next=ListNode(flag)return dummy.next?
轉載于:https://www.cnblogs.com/chengyuanqi/p/7136826.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的[算法题] Add Two Numbers的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 爬虫代理
- 下一篇: SpringMVC 学习笔记(五) 基