2. Add Two Numbers【medium】

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解法一:

 class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode * dummy = new ListNode(INT_MIN);
ListNode * head = dummy;
int carry = ; while (l1 != NULL && l2 != NULL) {
int sum = l1->val + l2->val + carry;
carry = sum / ;
head->next = new ListNode(sum % );
head = head->next;
l1 = l1->next;
l2 = l2->next;
} while (l1 != NULL) {
int sum = l1->val + carry;
carry = sum / ;
head->next = new ListNode(sum % );
head = head->next;
l1 = l1->next;
} while (l2 != NULL) {
int sum = l2->val + carry;
carry = sum / ;
head->next = new ListNode(sum % );
head = head->next;
l2 = l2->next;
} if (carry) {
head->next = new ListNode(carry);
head = head->next;
} head->next = NULL; return dummy->next;
}
};

写得太长了,下面有短码的方法

解法二:

 public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists(ListNode l1, ListNode l2) {
// write your code here
ListNode dummy = new ListNode();
ListNode tail = dummy; int carry = ;
for (ListNode i = l1, j = l2; i != null || j != null; ) {
int sum = carry;
sum += (i != null) ? i.val : ;
sum += (j != null) ? j.val : ; tail.next = new ListNode(sum % );
tail = tail.next; carry = sum / ;
i = (i == null) ? i : i.next;
j = (j == null) ? j : j.next;
} if (carry != ) {
tail.next = new ListNode(carry);
}
return dummy.next;
}
}

参考了九章的代码

解法三:

 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode preHead(), *p = &preHead;
int extra = ;
while (l1 || l2 || extra) {
int sum = (l1 ? l1->val : ) + (l2 ? l2->val : ) + extra;
extra = sum / ;
p->next = new ListNode(sum % );
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next;
}

参考了@ce2 的代码

解法四:

 class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// 题意可以认为是实现高精度加法
ListNode *head = new ListNode();
ListNode *ptr = head;
int carry = ;
while (true) {
if (l1 != NULL) {
carry += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
carry += l2->val;
l2 = l2->next;
}
ptr->val = carry % ;
carry /= ;
// 当两个表非空或者仍有进位时需要继续运算,否则退出循环
if (l1 != NULL || l2 != NULL || carry != ) {
ptr = (ptr->next = new ListNode());
} else break;
}
return head;
}
};

参考了九章的代码

2. Add Two Numbers【medium】的更多相关文章

  1. 167. Add Two Numbers【easy】

    You have two numbers represented by a linked list, where each node contains a single digit. The digi ...

  2. 544. Top k Largest Numbers【medium】

    Given an integer array, find the top k largest numbers in it.   Example Given [3,10,1000,-99,4,100] ...

  3. 82. Remove Duplicates from Sorted List II【Medium】

    82. Remove Duplicates from Sorted List II[Medium] Given a sorted linked list, delete all nodes that ...

  4. 75. Find Peak Element 【medium】

    75. Find Peak Element [medium] There is an integer array which has the following features: The numbe ...

  5. 92. Reverse Linked List II【Medium】

    92. Reverse Linked List II[Medium] Reverse a linked list from position m to n. Do it in-place and in ...

  6. 61. Search for a Range【medium】

    61. Search for a Range[medium] Given a sorted array of n integers, find the starting and ending posi ...

  7. 62. Search in Rotated Sorted Array【medium】

    62. Search in Rotated Sorted Array[medium] Suppose a sorted array is rotated at some pivot unknown t ...

  8. 74. First Bad Version 【medium】

    74. First Bad Version [medium] The code base version is an integer start from 1 to n. One day, someo ...

  9. 159. Find Minimum in Rotated Sorted Array 【medium】

    159. Find Minimum in Rotated Sorted Array [medium] Suppose a sorted array is rotated at some pivot u ...

随机推荐

  1. 【矩阵哈希】【哈希表】bzoj2351 [BeiJing2011]Matrix

    引用题解:http://blog.csdn.net/popoqqq/article/details/41084047 #include<cstdio> #include<cstrin ...

  2. 【C语言】 Linux下编译提示pow未定义引用

    如下代码: #include <stdio.h> // 调用基本输入输出函数库 #include <math.h> #define PI 3.14 // 定义常量 float ...

  3. 转载:oracle11G 已开启监听,但远程连接依旧无监听解决过程

    1.连接数据库显示无监听程序,首先查看服务器的oracle监听服务是否开启,服务名称:OracleOraDb11g_home1TNSListener(具体环境中可能不完全一样,但是认准TNSListe ...

  4. SVN安装中遇到的问题

    新的版本:1.9.5 必须使用Apache Portable Runtime Utility 1.5.4 Released没有安装的话需要先安装 需要安装apr.apr-util sqlite zli ...

  5. 几种常用的json序列化和反序列化工具介绍

    一.前言 Json序列化和反序列化工作中会时常用到,也是目前数据交互的常用格式,Rest风格的接口加上json格式的数据交互,真的是天作之合. 目前Json字符与Json对象的相互转换方式有很多,接下 ...

  6. C# 7 新特性-2

    在之前的C# 7 新特性博客中,我们谈到了Tuples,Record Type和Pattern Matching.这些都是C#新特性中最可能出现的.在本博客中,我们会提到更多的一些特性,虽然这些特性不 ...

  7. idea tomcat 怎样出现update classes and resources

    idea Tomcat 出现update classes and resources 出现热加载 正确配置应该是这个 在 Deployment (调度,部署) 中点击 + 选择war explored ...

  8. python使用pickle,json等序列化dict

    import pickle, json, csv, os, shutil class PersistentDict(dict): ''' Persistent dictionary with an A ...

  9. Oracle数据类型,函数与存储过程

    字符串类型    固定长度:char nchar    n 表示Unicode编码    可变长度: varchar2 nvarchar2 数字类型:number(P,S)P:整数位数,S小数位数   ...

  10. hibernate.cfg.xml文件连接mySql、Oracle、SqlServer配置

    1.连接mySql,文件配置如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibe ...