2. Add Two Numbers

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

def addtwonum(strings):
    list1 = []
    num = []
    flag = 0
    for i in range(len(strings)):
        if strings[i] == '+':
            lucy = strings[:i].strip().strip('(').strip(')')
            jerry  = strings[i+1:].strip().strip('(').strip(')')
    
    for i in range(len(lucy)):
        if lucy[i] == jerry[i]:
            list1.append(lucy[i])
        else:
            sum = int(lucy[i]) + int(jerry[i]) + flag
            if sum >= 10:
                flag = 1
                sum = sum-10
            else:
                flag = 0
            list1.append(str(sum))
    print(''.join(list1))
if __name__ == '__main__':
    addtwonum("(3 -> 4 -> 5) + (5 -> 6 -> 7)")
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • You are given two non-empty linked lists representing two...
    xxx亦凡桑閱讀 224評論 0 0
  • 上通信的課就跟室友一起刷題玩,結果讀題目讀了半天,好歹我也是過了四級的人啊,怎么能這樣,干脆百度題目意思…… 題目...
    做夢枯島醒閱讀 244評論 0 0
  • Description You are given two non-empty linked lists repr...
    CNSumi閱讀 249評論 0 0
  • 純屬湊個圖 也不知道是不是兩個月沒碰日記本了,要發霉了 最近發生的事情太多 雖然不能夠一件件寫下來 但還是想寫點什...
    幸福_是你給的在乎閱讀 194評論 0 0
  • 唯一不變的就是改變。 沉沒成本,及時止損。 克服恐懼。 隨著時間的流逝,天地萬物都在改變。曾經嶄新的樓房,早已披上...
    cuicui88閱讀 307評論 0 0