LeetCode题解:Add Two Numbers
2015-08-28 10:45
337 查看
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
题意:两个链表各自代表一个正整数,求它们的和
解题思路:加法运算
代码:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题意:两个链表各自代表一个正整数,求它们的和
解题思路:加法运算
代码:
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); ListNode head = result; int sum = 0; while(l1 != null || l2 != null){ sum /= 10; if(l1 != null){ sum += l1.val; l1 = l1.next; } if(l2 != null){ sum += l2.val; l2 = l2.next; } head.next = new ListNode(sum % 10); head = head.next; } if(sum / 10 == 1){ head.next = new ListNode(1); } return result.next; } }
相关文章推荐
- C#数字、16进制字符串和字节之间互转
- bzoj4029[HEOI2015]定价
- superdemo
- 发工资咯:) 2021 (完全背包)
- Redis HASH 操作类型封装
- 软工视频总结Part Four
- jquery设置控件位置的方法
- git本地有冲突的时候,pull代码
- ReactiveCocoa Documents 翻译(基于版本V2.5)
- Oracle 10g新增DROP DATABASE命令
- zoj 2587 Unique Attack 【判断最小割是否唯一】
- git log显示时间修改
- iOS AutoLayout自动布局中级开发教程(7)-底部顶部baseLine基线对齐
- CoreAnimation-01-CALayer核心要点及实例解析
- 【二十】一个面试题
- 软件任务的进度安排
- iOS学习 - scrollView(图片查看器)
- PHP实现螺旋矩阵(螺旋数组)
- 线性分类器:Fisher线性判别
- jquery获取html元素的绝对位置和相对位置的方法