Leetcode Add Two Numbers
2016-07-06 00:47
417 查看
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
Difficulty: Medium
/**
* 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) {
int temp = 0;
ListNode res = new ListNode(1);
ListNode curr = res;
while(l1 != null || l2 != null){
int value = temp;
if(l1 != null){
value += l1.val;
l1 = l1.next;
}
if(l2 != null){
value += l2.val;
l2 = l2.next;
}
if(value >= 10){
temp = 1;
value = value - 10;
}
else{
temp = 0;
}
curr.next = new ListNode(value);
curr= curr.next;
}
if(temp == 1){
curr.next = new ListNode(1);
}
return res.next;
}
}
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Difficulty: Medium
/**
* 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) {
int temp = 0;
ListNode res = new ListNode(1);
ListNode curr = res;
while(l1 != null || l2 != null){
int value = temp;
if(l1 != null){
value += l1.val;
l1 = l1.next;
}
if(l2 != null){
value += l2.val;
l2 = l2.next;
}
if(value >= 10){
temp = 1;
value = value - 10;
}
else{
temp = 0;
}
curr.next = new ListNode(value);
curr= curr.next;
}
if(temp == 1){
curr.next = new ListNode(1);
}
return res.next;
}
}
相关文章推荐
- HDU 5289 Assignment(线段树)
- 一种c#深拷贝方式完胜java深拷贝(实现上的对比)
- CMake 介绍 & CMakeList.txt
- 老毛桃U盘启动盘制作工具V20140501完美贡献版
- 老毛桃U盘启动盘制作工具V20140501完美贡献版
- 稳定排序和不稳定排序
- 102. Binary Tree Level Order Traversal
- django-模板初探
- Mac OS X系统下编译运行C代码
- 前端案例--纯CSS3美化复选框
- 类和成员变量
- Java编程思想之并发
- Spring AOP 简介以及简单用法
- RC4密码算法实现
- 集合类Collection
- SpringMVC学习系列(4) 之 数据绑定-1
- ajax(一)
- c++ visual studio 2013连接mysql
- 命令行启动mysql服务
- Quiz 6b_question#7