题目描述: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. 【bzoj1013】[JSOI2008]球形空间产生器sphere

    1013: [JSOI2008]球形空间产生器sphere Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 4530  Solved: 2364[Subm ...

  2. Mrt render

    mutil render target Pixel shder输出一个结构体 Out.f4Color Out.f4Normal 这步在渲染物体的shader里 在application setcolo ...

  3. centos6.5安装图形界面,windows远程linux图形界面

    1. 查询是否已安装图形界面 yum grouplist |more 在grouplist的输出结果中的“Installed Groups:”部分中,如果你能找到“X Window System”和G ...

  4. Codeforces Round #243 (Div. 1) A题

    http://codeforces.com/contest/425/problem/A 题目链接: 然后拿出这道题目是很多人不会分析题目,被题目吓坏了,其中包括我自己,想出复杂度,一下就出了啊!真是弱 ...

  5. CodeForces 321A

    A. Ciel and Robot time limit per test 1 second memory limit per test 256 megabytes input standard in ...

  6. NGUI 自定义 Drag Item Script

    最近要实现一个NGUI效果. 查看了一下,NGUI有个自带 UIDragDropItem.cs 的组件进过修改后即可以实现. 下面贴上UI布局,代码: mDragDropItem.cs using U ...

  7. jQuery scroll事件

    scroll事件适用于window对象,但也可滚动iframe框架与CSS overflow属性设置为scroll的元素. $(document).ready(function () { //本人习惯 ...

  8. 2016年度 JavaScript 展望(上)

    [编者按]本文作者为资深 Web 开发者 TJ VanToll, TJ 专注于移动端 Web 应用及其性能,是<jQuery UI 实践> 一书的作者. 本文系 OneAPM 工程师编译呈 ...

  9. poj 2749

    Building roads Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 6091   Accepted: 2046 De ...

  10. iOS导航栏-导航栏透明

    设置一张透明图片:nav_bargound.png  //导航栏背景     [self.navigationController.navigationBar setBackgroundImage:[ ...