博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 【 Add Two Numbers 】 python 实现
阅读量:5975 次
发布时间:2019-06-20

本文共 2069 字,大约阅读时间需要 6 分钟。

题目

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

 

代码:oj测试通过 Runtime: 171 ms

1 # Definition for singly-linked list. 2 # class ListNode: 3 #     def __init__(self, x): 4 #         self.val = x 5 #         self.next = None 6  7 class Solution: 8     # @return a ListNode 9     def addTwoNumbers(self, l1, l2):10         if l1 is None:11             return l212         if l2 is None:13             return l114         15         dummyhead = ListNode(0)16         p = ListNode(0)17         dummyhead.next = p18         19         jinwei = 020         while l1 is not None and l2 is not None:21             curr_total = l1.val + l2.val + jinwei22             l1 = l1.next23             l2 = l2.next24             curr_digit = curr_total % 1025             jinwei = curr_total / 1026             curr_node = ListNode(curr_digit)27             p.next = curr_node28             p = p.next29             30         if l1 is not None:31             while l1 is not None:32                 curr_total = l1.val + jinwei33                 l1 = l1.next34                 curr_digit = curr_total % 1035                 jinwei = curr_total / 1036                 curr_node = ListNode(curr_digit)37                 p.next = curr_node38                 p = p.next39         if l2 is not None:40             while l2 is not None:41                 curr_total = l2.val + jinwei42                 l2 = l2.next43                 curr_digit = curr_total % 1044                 jinwei = curr_total / 1045                 curr_node = ListNode(curr_digit)46                 p.next = curr_node47                 p = p.next48         49         if jinwei == 1:50             curr_node = ListNode(1)51             p.next = curr_node52         53         return dummyhead.next.next

思路

就是加法运算 注意两条链表上所有值计算过后 是否有进位;如果有进位 需要再处理一下。

转载于:https://www.cnblogs.com/xbf9xbf/p/4228421.html

你可能感兴趣的文章
PHP学习笔记2:文件
查看>>
jsrender简单使用
查看>>
window mysql-bin 转化为可读模式
查看>>
redis 安装及php扩展编译安装
查看>>
MPAndroidChart---饼状图PieChart
查看>>
PHP中基于b2core框架内部的网页上Html输出生成Word的处理
查看>>
采用Servlet Listener方式运行Liquibase
查看>>
TCP-IP 学习(三) TCP
查看>>
对比两个无序整形数组相似度问题算法
查看>>
批量有效地修改package名
查看>>
android或ios app请求参数格式
查看>>
Camera Vision - video surveillance on C#
查看>>
如何理解网络连接中的"3次握手"?
查看>>
使用Dubbo服务出现java.io.IOException: invalid constant type: 18异常解决办法
查看>>
一条命令完成砸壳
查看>>
PYKit目录
查看>>
JSON使用总结
查看>>
php-redis中文帮助手册_系统相关_config_eval_evalSha_script...
查看>>
Tomcat Context配置
查看>>
CentOS6.5安装ntopng
查看>>