题目描述: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.(给你两个链表,表示两个非负整数。数字在链表中按反序存储,例如342在链表中为2->4->3。链表每一个节点包含一个数字(0-9)。计算这两个数字和并以链表形式返回。)

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8                                     (即:342+465= 807)

分析:由上述描述知,要注意以下几点,

(1)因为存储是反过来的,即数字342存成2->4->3,所以要注意进位是向后的;

(2)边界条件:链表l1或l2为空时,直接返回;

(3)链表l1和l2长度可能不同,因此要注意处理某个链表剩余的高位;

(4)2个数相加,可能会产生最高位的进位,因此要注意在完成以上(1)-(3)的操作后,判断进位是否为0,不为0则需要增加结点存储最高位的进位。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* sum;
sum = new ListNode(l1->val + l2->val);
ListNode* p = sum;
l1 = l1->next;
l2 = l2->next;
while(l1 != NULL || l2 != NULL || p->val > 9)
{
p->next = new ListNode(p->val / 10);
p->val %= 10;//判断是否产生进位
p = p->next; //处理l1或l2可能的剩余高位
if(l1)
{
p->val += l1->val;
l1 = l1->next;
} if(l2)
{
p->val += l2->val;
l2 = l2->next;
}
} return sum;
}
};

 其他解法:

class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int tmp=0;
ListNode rs(0), *r=&rs, *p=l1, *q=l2;
while(p!=NULL||q!=NULL||tmp){
tmp=tmp+(p==NULL?0:p->val)+(q==NULL?0:q->val);
r->next=new ListNode(tmp%10);
r=r->next;
p=(p==NULL?p:p->next);
q=(q==NULL?q:q->next);
tmp=tmp/10;
}
return rs.next;
}
};

  

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

class Solution {
public:
string addBinary(string a, string b) {
string res;
int i = a.size(), j = b.size(), cur = 0;
while(i || j || cur) {
cur += (i ? a[(i--)-1] -'0' : 0) + (j ? b[(j--)-1] -'0' : 0);
res = char(cur%2 + '0') + res;
cur /= 2;
}
return res;
}
};

注:字符在计算机里是用数字表示的,即ascill 码。如:a[1]是'1' ,字符'1'的ascii码是49,而字符'0'的ascii码是48 ,这样a[1]-'0'就是49-48 求得的就是数字1,这样就把a[1]里边存的数字字符转换成了整形数值。

或:(和上一种差不多)
class Solution {
public:
string addBinary(string a, string b) {
int size_a = a.size(), size_b = b.size(), extra = 0;
string res;
while(size_a > 0 || size_b > 0 || extra > 0) {
int i_1 = size_a > 0 ? int(a.at(-1 + size_a--)) - int('0') : 0;
int i_2 = size_b > 0 ? int(b.at(-1 + size_b--)) - int('0') : 0;
int sum = i_1 + i_2 + extra, append = sum % 2;
extra = sum / 2;
res.append(1, char('0' + append));
}
return string(res.rbegin(), res.rend());
}
};

  或:

class Solution {
public:
string addBinary(string a, string b) {
int carry = 0;
int pa = a.length() - 1;
int pb = b.length() - 1;
string& res = pa > pb ? a : b;
int p = max(pa, pb);
int tmp;
while ( pa >= 0 && pb >= 0 )
{
tmp = a[pa--] - '0' + b[pb--] - '0' + carry;
res[p--] = (tmp & 1) + '0';
carry = tmp >> 1;
}
while ( p >= 0 )
{
tmp = res[p] - '0' + carry;
res[p--] = (tmp & 1) + '0';
carry = tmp >> 1;
}
if ( carry )
{
res = '1' + res;
}
return res;
}
};

  

 

 

leetcode:Add Two Numbers的更多相关文章

  1. LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters

    LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters 题记 刷LeetCod ...

  2. LeetCode:1. Add Two Numbers

    题目: LeetCode:1. Add Two Numbers 描述: Given an array of integers, return indices of the two numbers su ...

  3. [LeetCode] 445. Add Two Numbers II 两个数字相加之二

    You are given two linked lists representing two non-negative numbers. The most significant digit com ...

  4. LeetCode 面试:Add Two Numbers

    1 题目 You are given two linked lists representing two non-negative numbers. The digits are stored in ...

  5. LeetCode #002# Add Two Numbers(js描述)

    索引 思路1:基本加法规则 思路2:移花接木法... 问题描述:https://leetcode.com/problems/add-two-numbers/ 思路1:基本加法规则 根据小学学的基本加法 ...

  6. [Leetcode Week15] Add Two Numbers

    Add Two Numbers 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/add-two-numbers/description/ Descrip ...

  7. [LeetCode] 2. Add Two Numbers 两个数字相加 java语言实现 C++语言实现

    [LeetCode] Add Two Numbers 两个数字相加   You are given two non-empty linked lists representing two non-ne ...

  8. [LeetCode] 2. Add Two Numbers 两个数字相加

    You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...

  9. LeetCode之Add Two Numbers

    Add Two Numbers 方法一: 考虑到有进位的问题,首先想到的思路是: 先分位求总和得到 totalsum,然后再将totalsum按位拆分转成链表: ListNode* addTwoNum ...

随机推荐

  1. Spring Junit4 Test

    捣鼓了差不多一天...终于把"No Session found for current thread"问题解决了 环境:Spring 4.0.6 RELEASE + Hiberna ...

  2. 实现IDisposable接口的模式

    代码: public class Class2 : IDisposable { ~Class2() { Dispose(false); } public void Dispose() { Dispos ...

  3. HDU1005Number Sequence(找规律)

    Number Sequence Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)T ...

  4. ASP.NET Session的七点认识

    原文:http://kb.cnblogs.com/page/108689/ ASP.NET Session的使用当中我们会遇到很多的问题,那么这里我们来谈下经常出现的一些常用ASP.NET Sessi ...

  5. PHP 中 Date 函数与实际时间相差8小时的解决方法

    PHP 中的 date() 函数显示的时间是格林威治时间,和北京时间正好相差8个小时,其他时间相关的函数,如 strtotime() 也有相同的问题,同样可以通过下面的方法来解决: 1. 修改php. ...

  6. POJ 3662

    Telephone Lines Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4591   Accepted: 1693 D ...

  7. Bit-Map

    昨日读July大神<教你如何迅速秒杀掉:99%的海量数据处理面试题>博客,有这么一题与大家分享: 给40亿个不重复的unsigned int的整数,没排过序的,然后再给一个数,如何快速判断 ...

  8. 传说中的WCF(7):“单向”&“双向”

    在WCF中,服务器与客户端的通讯有单向(单工)和双向(双工)之分.要说有什么形式上的表现,那就是单向与双向生成的SOAP不同,咱们先放下代码不说.但通常情况下,我们也不太需要去研究生成的SOAP是啥样 ...

  9. (4)用opengl读入off文件生成可执行文件把模型显示出来(未完待续)

    ·找了好几个程序,好像都达不到我的要求,去教程里看看吧! 在往上抛出了这问题,好几天才有人回答,我已经找到程序了 正好的他的分析对我分解程序很有用 这是一个难度比较高的 首先你要分析.off文件结构, ...

  10. 【hdu1573-X问题】拓展欧几里得-同余方程组

    http://acm.hdu.edu.cn/showproblem.php?pid=1573 求小于等于N的正整数中有多少个X满足: X mod a0 = b0 X mod a1 = b1 …… X  ...