Add Two Numbers
2015-08-06 14:02
281 查看
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
题目解析:有进位的链表合并,主要是考虑最后一次进位的情况,比如【2,7】【3,7】——>【5,1,4】
解法:链表问题一定要注意是否是空指针,然后在合并中分为3类处理,俩个链表均有元素,A链表完结,B链表完结,AC代码如下
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目解析:有进位的链表合并,主要是考虑最后一次进位的情况,比如【2,7】【3,7】——>【5,1,4】
解法:链表问题一定要注意是否是空指针,然后在合并中分为3类处理,俩个链表均有元素,A链表完结,B链表完结,AC代码如下
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { // 安全性检查 if (l1 == null || l2 == null) { return null; } // 考虑有进位 int carry = 0; ListNode result = new ListNode(0); ListNode ponit = result; //分三种情况讨论比较好理解 while (l1 != null && l2 != null) { int sum = l1.val + l2.val+carry; ponit.next = new ListNode(sum % 10); carry = sum / 10; l1 = l1.next; l2 = l2.next; ponit = ponit.next; } while (l1 != null) { int sum = carry + l1.val; ponit.next = new ListNode(sum % 10); carry = sum / 10; l1 = l1.next; ponit = ponit.next; } while (l2 != null) { int sum = carry + l2.val; ponit.next = new ListNode(sum % 10); carry = sum / 10; l2 = l2.next; ponit = ponit.next; } //防止最后一位仍有进位 if(carry!=0){ ponit.next = new ListNode(carry); } return result.next; } }
相关文章推荐
- 我的高效编程的秘诀:自动化你的编程工作
- caffe源码解析 — caffe.proto
- Frida-跨平台注入工具基础篇
- Add Two Numbers
- 医保结算单的“自费”、“自理”、“自负”分别是什么意思?
- 第四题
- JNI Hook java层方法
- Web 服务编程,REST 与 SOAP
- android学习笔记之SQLite数据库
- css用法大全
- 写给同事的前端学习路线
- Win10正式版暗藏黑色主题模式怎么开启?
- sqlserver数据类型转换(将 nvarchar 转换为数据类型 numeric 时出现算术溢出错误)
- iOS用户点击事件处理
- Atom飞行手册翻译: 3.9 从Textmate中转换
- Linux打包命令 - tar
- jQuery设置和移除文本框默认值
- Linux打包命令 - tar
- hdoj 1242 Rescue
- 面向接口