leetcode:Add Two Numbers
题目描述: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的更多相关文章
- LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters
LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters 题记 刷LeetCod ...
- LeetCode:1. Add Two Numbers
题目: LeetCode:1. Add Two Numbers 描述: Given an array of integers, return indices of the two numbers su ...
- [LeetCode] 445. Add Two Numbers II 两个数字相加之二
You are given two linked lists representing two non-negative numbers. The most significant digit com ...
- LeetCode 面试:Add Two Numbers
1 题目 You are given two linked lists representing two non-negative numbers. The digits are stored in ...
- LeetCode #002# Add Two Numbers(js描述)
索引 思路1:基本加法规则 思路2:移花接木法... 问题描述:https://leetcode.com/problems/add-two-numbers/ 思路1:基本加法规则 根据小学学的基本加法 ...
- [Leetcode Week15] Add Two Numbers
Add Two Numbers 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/add-two-numbers/description/ Descrip ...
- [LeetCode] 2. Add Two Numbers 两个数字相加 java语言实现 C++语言实现
[LeetCode] Add Two Numbers 两个数字相加 You are given two non-empty linked lists representing two non-ne ...
- [LeetCode] 2. Add Two Numbers 两个数字相加
You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...
- LeetCode之Add Two Numbers
Add Two Numbers 方法一: 考虑到有进位的问题,首先想到的思路是: 先分位求总和得到 totalsum,然后再将totalsum按位拆分转成链表: ListNode* addTwoNum ...
随机推荐
- WP手机升级WIN10被PIN码锁定
WP8.1手机升级WIN10后,需要输入PIN码(不知道啊),多次输入(1234,0000,8888 ...)后被锁定,无法使用手机(郁闷), 重启无数次,提示由于多次输入PIN码,手机无法使用(天啊 ...
- 研究AVCaptureDevice
一.Apple Resource 1. wwdc 2014: Camera Caputre: Manual Controls 2. Exaple code: AVCam&AVCamManul ...
- STMPClient 发送邮件显示 不允许使用邮件名称.
在.net 2.0,3.5, 针对某些邮箱(还不清楚是什么样的邮件) , 使用微软自带的DLL发送邮件会提示不允许使用邮件名称 .... 使用Jmail可以发送. 解决方案: 1. ...
- 贴代码—CF230 DIV1 B
题目在此: http://codeforces.com/contest/392/problem/B 一直理解错了一句话,以为是用最小的move求最小的花费, 读错题目的有木有!!! 不懂汉诺塔的原理有 ...
- ASP.NET 处理get/post数据方式
1.GET方式 NameValueCollection coding; coding = HttpUtility.ParseQueryString(Request.Url.Query, Encodin ...
- HDU 3642 Get The Treasury (线段树扫描线,求体积并)
参考链接 : http://blog.csdn.net/zxy_snow/article/details/6870127 题意:给你n个立方体,求覆盖三次以上(包括三次)的区域的体积 思路:先将z坐标 ...
- JavaWeb-JDK下载安装
JDK官方下载地址:http://www.oracle.com/index.html JDK下载: 64位的下64的 JDK安装:(这是32位的) JDK部署测试:(配置环境变量) JAVA_HOME ...
- JSON.stringify 函数 (JavaScript)
在bsrck项目中,使用jQuery.Form.js的ajaxSubmit时,遇到有文件上传的form提交,在firefox和chrome浏览器中测试,报Bad Request的错误,经查代码后发现是 ...
- [转载] select, poll和epoll的区别
源地址:http://sheepxxyz.blog.163.com/blog/static/61116213201022003513530/ 随着2.6内核对epoll的完全支持,网络上很多的文章和示 ...
- java编译错误:varargs 方法的非 varargs 调用
转自:http://www.blogjava.net/ideame/archive/2007/03/23/105849.html 警告: 最后一个参数使用了不准确的变量类型的 varargs 方法的非 ...