题目描述: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. Effective Java总结

    规则1. 用静态工厂方法代替构造器 例子: public class Example { } public class StaticFactory { //valueOf/Of/getInstance ...

  2. JS范围

    JS API-->DOM/PoneGap/Cordova/Android/NodeJS JS OOP

  3. jquery easyui tab加载内容的几种方法

    转:http://my.oschina.net/u/2331760/blog/391937?fromerr=saqeoxxB jQuery Easyui 的tabs插件有两种方式加载某个tab(标签页 ...

  4. Solr笔记--转载

    Solr 是一种可供企业使用的.基于 Lucene 的搜索服务器,它支持层面搜索.命中醒目显示和多种输出格式.在这篇分两部分的文章中,Lucene Java™ 的提交人 Grant Ingersoll ...

  5. LCT模板

    之前一直用的LCT模板,因为其实个人对LCT和Splay不是很熟,所以用起来总觉得略略的坑爹,过了一段时间就忘了,但事实上很多裸的LCT要改的东西是不多的,所以今天写了些注释,以后可能套起模板来会得心 ...

  6. Android屏幕适应详解(二)

    android应用自适应多分辨率的解决方法 1. 首先是建立多个layout文件夹(drawable也一样).  在res目录下建立多个layout文件夹,文件夹名称为layout-800x480等. ...

  7. Full GC有关问题学习分析(转载)

    网站持久代引发Full GC问题分析 现状: Dragoon(监控系统)的日报显示trade_us_wholelsale(美国wholesale集群),日均Young GC次数25w次左右,应用暂停2 ...

  8. opencv face-detection 代码分析 (1)人脸识别后的数据

    2014,3,16   老师的工作建议如下:   1. 与四民沟通下,把openCV这边的源代码和调用接口发给四民同时抄送给我. 2. 根据openCV的实时检测结果,实现对屏幕的调整(下周一前基本实 ...

  9. Linux之select系统调用_1

    SYNOPSIS /* According to POSIX.1-2001 */ #include <sys/select.h> /* According to earlier stand ...

  10. MyEclipse 2015 CI

    系统 win8.1 MyEclipse 2015 CI 激活后可用 激活工具 地址:http://download.csdn.net/detail/trep10000/8305577