【LeetCode】C# 2、Add Two Numbers
来源:互联网 发布:mac 网站编辑 编辑:程序博客网 时间:2024/06/10 15:04
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
这个题目要考虑进位,考虑ListNode长度不等的问题,以及考虑ListNode长度走完之后还剩一个进位的情况。
所以我建了三个指针和新建一个result,先走完两个ListNode相加的部分,然后是单独的部分,最后加上进位。
public class Solution { public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { ListNode one = l1, two = l2; ListNode res = new ListNode(0); ListNode three = res; int sum=0; while(one!=null && two!=null){ three.next = new ListNode((one.val+two.val+sum)%10); sum=(one.val+two.val+sum)/10; one=one.next; two=two.next; three=three.next; } while(one!=null){ three.next = new ListNode((one.val+sum)%10); sum=(one.val+sum)/10; one=one.next; three=three.next; } while(two!=null){ three.next = new ListNode((two.val+sum)%10); sum=(two.val+sum)/10; two=two.next; three=three.next; } if(sum!=0) three.next = new ListNode(1); return res.next; }}
阅读全文
0 0
- 【LeetCode】C# 2、Add Two Numbers
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [leetcode 2] Add Two Numbers
- [Leetcode] 2 - Add Two Numbers
- LeetCode 2:《Add Two Numbers》
- LeetCode | #2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [Leetcode]2Add Two Numbers
- leetcode #2 Add Two Numbers
- leetcode-2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [leetcode] #2 Add Two Numbers
- LeetCode-2 Add Two Numbers
- LeetCode-2-Add Two Numbers
- Leetcode[2] Add Two Numbers
- LeetCode 2 Add Two Numbers
- 班级大讨论——论英语七选五
- NOIP2014提高组——解方程(equation)
- 12. 组合模式
- Mybatis+Spring+SpringMVC面试题.1
- (POJ 1847)Tram 简单最短路 spfa
- 【LeetCode】C# 2、Add Two Numbers
- Centos改变文件权限chmod
- Python自动发邮件
- HTML(七) 表格
- Luck and Love(二维线段树单点更新+区间查询+模板)
- nodejs代码段(六)
- 【深入PHP 面向对象】读书笔记(十三)
- easyui手风琴菜单
- Java 语言概述与开发环境(一)