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. [BZOJ1559]密码

    数据范围特别小,考虑状压DP 因为要求给定的字符串在母串中出现,所以可以用AC自动机辅助DP 因为AC自动机不能处理模式串互相包含的情况,所以先把互相包含的串去掉(暴力就行,数据范围太小) 因为要状压 ...

  2. 【dfs】【高斯消元】【异或方程组】bzoj1770 [Usaco2009 Nov]lights 燈 / bzoj2466 [中山市选2009]树

    经典的开关灯问题. 高斯消元后矩阵对角线B[i][i]若是0,则第i个未知数是自由元(S个),它们可以任意取值,而让非自由元顺应它们,得到2S组解. 枚举自由元取0/1,最终得到最优解. 不知为何正着 ...

  3. 【可持久化Trie】【set】bzoj3166 [Heoi2013]Alo

    枚举每个数,计算以其为次大数的最大区间,显然,只需要用这个区间的答案 对 答案进行更新即可. 找到每个数右侧.左侧第1.2个比它大的数,然后分类讨论一下即可. 找到的过程中把数sort以后,从大到小把 ...

  4. 【左偏树】HDU1512-Monkey King

    [题目大意] 在一个森林里住着N(N<=10000)只猴子.在一开始,他们是互不认识的.但是随着时间的推移,猴子们少不了争斗,但那只会发生在互不认识(认识具有传递性)的两只猴子之间.争斗时,两只 ...

  5. 使用virtualenv为应用提供了隔离的Python运行环境

    在开发Python应用程序的时候,系统安装的Python3只有一个版本:3.4.所有第三方的包都会被pip安装到Python3的site-packages目录下. 如果我们要同时开发多个应用程序,那这 ...

  6. 在C#中快速查询文件

    相信使用过Everything的人都对其超快的搜索速度印象非常深刻,它的主要原理是通过扫描NTFS磁盘的USN Journal读取的文件列表,而不是磁盘目录,由于USN Journal非常小,因此能实 ...

  7. Oracle Service Bus Socket Adapter调整的参数

    之前在一个客户中做压力测试时候Oracle Service Bus性能大概达到900tps左右,和客户期望的1600tps有很大差距. 在研究了Socket Adapter的工作原理之后,判断可能是O ...

  8. python的 json.dumps 中文编码

    python的 json.dumps 中文编码 # -- coding: utf-8 -- 的作用:文件内容以utf-8编码 json.dumps 序列化时对中文默认使用的ascii编码, print ...

  9. Solr6.6.0 用 SimplePostTool与界面dataimport索引方式区别

    通过测试发现用SimplePostTool与solr界面dataimport索引数据的结果有如下区别: 1.SimplePostTool索引数据对结构化数据文件索引比较合适,比如csv/json/xm ...

  10. 【招聘App】—— React/Nodejs/MongoDB全栈项目:消息列表

    前言:最近在学习Redux+react+Router+Nodejs全栈开发高级课程,这里对实践过程作个记录,方便自己和大家翻阅.最终成果github地址:https://github.com/66We ...