LeetCode 002 Add Two Numbers
2015-10-28 16:05
375 查看
题目描述
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
代码
[code] public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null && l2 == null) { return null; } if (l1 == null) { return l2; } if (l2 == null) { return l1; } ListNode p1 = l1; ListNode p2 = l2; // 进位标志 int carry = 0; ListNode head = new ListNode(0); // result.next为结果 ListNode result = head; while (carry != 0 || p1 != null || p2 != null) { int v1 = 0; if (p1 != null) { v1 = p1.val; p1 = p1.next; } int v2 = 0; if (p2 != null) { v2 = p2.val; p2 = p2.next; } int tmp = v1 + v2 + carry; carry = tmp / 10;// 存储进位 head.next = new ListNode(tmp % 10); head = head.next; } return result.next; }
相关文章推荐
- Html 中表格导出生成excel文件,解决中文导出失败问题。
- IOS笔记UI--固定宽度,根据内容动态改变高度
- web app iphone4 iphone5 iphone6 iphone6 Plus响应式布局 适配代码
- Java获取客户端IP
- Linux上oracle怎么启动OEM
- Android 中 px和dp 的转换
- Python 3 安装 lxml 报错Unable to find vcvarsall.bat的解决方法
- about dict
- 学习过程中的一些疑问
- iOS BLE开发关键步骤
- adaboost算法浅析
- 项目中某些静态库缺少,或者编译环境的问题造成的相关编译错误(Undefined symbols for architecture x86_64:)
- opencv源码解析之(5):CommandLineParser类的简单理解
- ssh 安装及登录提示:connection refused(ssh: connect to host XX.XX.XX.XX port 22: Connection refused)的解决办法
- javascript——defer和async的区别
- 被蚊子和自己搞毁的一天
- ecshop分页
- webservice 绕过证书验证调用https接口
- Java中的Enum的使用与分析
- jsp+ajax实现的局部刷新较验验证码(onblur事件触发较验)