[LeetCode]-algorithms-Add Two Numbers
2016-03-28 10:06
387 查看
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
分析:计算两个链表的和
解法:这道题的关键点在于节点的计算方式:sum = node1 + node2; new_node = sum%10; sum = sum/10;
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry =0;
ListNode newHead = new ListNode(0);
ListNode p1 = l1, p2 = l2, p3=newHead;
while(p1 != null || p2 != null){
if(p1 != null){
carry += p1.val;
p1 = p1.next;
}
if(p2 != null){
carry += p2.val;
p2 = p2.next;
}
p3.next = new ListNode(carry%10);
p3 = p3.next;
carry /= 10;
}
if(carry==1)
p3.next=new ListNode(1);
return newHead.next;
}
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析:计算两个链表的和
解法:这道题的关键点在于节点的计算方式:sum = node1 + node2; new_node = sum%10; sum = sum/10;
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry =0;
ListNode newHead = new ListNode(0);
ListNode p1 = l1, p2 = l2, p3=newHead;
while(p1 != null || p2 != null){
if(p1 != null){
carry += p1.val;
p1 = p1.next;
}
if(p2 != null){
carry += p2.val;
p2 = p2.next;
}
p3.next = new ListNode(carry%10);
p3 = p3.next;
carry /= 10;
}
if(carry==1)
p3.next=new ListNode(1);
return newHead.next;
}
相关文章推荐
- leangoo大讲堂--北京站
- Django 源码阅读
- MongoClient类参考文档
- SENGO森果汇聚婚礼一切美好
- django 源码阅读二 命令check
- Django-Form表单(验证、定制、错误信息、Select)
- 2016/3/27 分页 共X条数据 本页x条 本页从x-y条 x/y页 首页 上一页 123456 下一页 末页 pagego echo $page->fpage(7,6,5,4,3,2,1,0);
- golang笔记——并发
- Django进阶(路由系统、中间件、缓存、Cookie和Session、Ajax发送数据
- 在Google Maps 上点击标签显示说明并保持不消失
- 在Google Maps 上点击标签后显示说明
- 如何在Google Maps 添加多个标记
- Google开源单元测试框架Google Test:VS2012 配置
- golang笔记——函数与方法
- HDU Let's go to play
- 如何在 Google 地图中添加标记和说明
- 启动Genymotion模拟器时,显示The virtual device got no IP address
- gone fishing
- HDU--1533--Going Home--KM算法
- Go语言学习(九)文件操作