[Lintcode] Add Two Numbers I && II
2015-11-17 11:52
323 查看
Add Two Numbers
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored inreverseorder, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example
Given
7->1->6 + 5->9->2. That is,
617 + 295.
Return
2->1->9. That is
912.
Given
3->1->5and
5->9->2, return
8->0->8.
SOLUTION:
很简单,就是对应加法,重新见一个linkedlist,然后还要考虑进位,要一个进位count,位数加法还要加上count。
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param l1: the first list * @param l2: the second list * @return: the sum list of l1 and l2 */ public ListNode addLists2(ListNode l1, ListNode l2) { if (l1 == null){ return l2; } if (l2 == null){ return l1; } l1 = reverse(l1); l2 = reverse(l2); ListNode head = add(l1, l2); return reverse(head); } private ListNode reverse(ListNode head){ if (head == null){ return null; } ListNode pre = null; while (head != null){ ListNode temp = head.next; head.next = pre; pre = head; head = temp; } return pre; } private ListNode add(ListNode l1, ListNode l2){ if (l1 == null){ return l2; } if (l2 == null){ return l1; } int sum = 0; int count = 0; ListNode dummy = new ListNode(0); ListNode curr = dummy; while (l1 != null && l2 != null){ sum = l1.val + l2.val + count; curr.next = new ListNode(sum % 10); count = sum / 10; curr = curr.next; l1 = l1.next; l2 = l2.next; } while (l1 != null){ sum = l1.val + count; curr.next = new ListNode(sum % 10); count = sum / 10; curr = curr.next; l1 = l1.next; } while (l2 != null){ sum = l2.val + count; curr.next = new ListNode(sum % 10); count = sum / 10; curr = curr.next; l2 = l2.next; } if (count != 0){ curr.next = new ListNode(count); } return dummy.next; } }
View Code
相关文章推荐
- Android Wi-Fi Display(Miracast)介绍
- 利用扇区编辑手工恢复删除的文件
- 校验数字签名防止 apk 被二次打包 - Java层校验(大众点评为例)
- 真不敢相信!网站一个月百度权重竟然升到2
- outlook设置接收邮件的时间--MAC版
- Handler Looper MessageQueue之Looper
- RAID分类整合
- Oracle使用DBSTART开机启动
- Air Raid(最小路径覆盖)
- Java代码探查hbase表结构及数据
- Linux服务器上安装使用TCPCopy来获取用户访问流量
- day4 python学习随笔
- 代理模式vs适配器模式vs外观模式
- ubuntu14.04,配置GOPATH(GO语言开发代码存放目录)
- 接口中的常量
- 配置ruby环境
- ubuntu14.04,配置GOPATH(GO语言开发代码存放目录)
- PythonOS库练习——模拟linux文件管理命令
- Android的基本控件,及其继承关系
- 【AJAX】给你不一样的用户体验