class Solution {
public:
string addBinary( string a, string b) {
int a1=a.size();
int b1=b.size();
while(a1<b1)
{
a='0'+a;
++a1;
}
while(a1>b1)
{
b='0'+b;
++b1;
}
for(int i=a1;i>0;--i)
{
a[i]=a[i]-'0'+b[i];
if (a[i] >= '2')
{
a[i-1]=a[i-1]+1;
a[i]=(a[i]-'0')%2+'0';
}
}
}
a[0] = a[0] - '0' + b[0]; //将ab的第0位相加
if (a[0] - '0' >= 2)
{
a[0] = (a[0]-'0')%2+'0';
a='1'+a;
}
return a;
}
};
这里 if (a[i] >= '2') { a[i-1]=a[i-1]+1; a[i]=(a[i]-'0')%2+'0'; }
一定要注意的是: 每次进位为2时,就一定要写成 -‘0’再取余,要不然会产生错误。错误是什么原因我现在还不清楚。对于不熟练的内容,以后要写简单点,别怕麻烦。
剑指offer24:反转链表
根据经验,乐扣上的题都是不给头结点的,以后面试笔试时要问清楚可不可以带头结点。
以下是我的写法:(用到的是三指针的方法。)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr)
{
return nullptr;
}
struct ListNode* pre = nullptr;
struct ListNode* cur = head;
struct ListNode* tmp;
if (head->next != nullptr)
{
struct ListNode* tmp = head->next;
}
else {
return head;
}
while (cur->next != nullptr)
{
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
cur->next = pre;
return cur;
}
};
接下来是官方的写法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
可以看到,这种写法的巧妙之处在于:不用额外考虑head是否为空指针,以及设置的curr->next 是否为空。
因为第一行和最后一行的代码可以排除空指针。
1 ListNode* next = curr->next;
2 curr->next = prev;
3 prev = curr;
4 curr = next;
不好的一点就是空间上会有浪费,每次循环都设置一个结构体指针。
**方法2是递归、
**以下是我自己码的代码,核心代码如下 :每次返回的地址值的顺序:5->4->3->2->1( return head;)
ListNode* p = reverseList1(head->next);
p->next = head;
return head;
值5的地址由静态变量记载。
static ListNode* ip;
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr)
{
return nullptr;
}
if (head->next == nullptr)
{
return head;
}
ListNode* p = reverseList1(head->next);
p->next = head;
head->next = nullptr;
return ip;
}
ListNode* reverseList1(ListNode* head) {
if (head->next == nullptr)
{
ip = head;
return head;
}
ListNode* p = reverseList1(head->next);
p->next = head;
return head;
}
};
另一种递归写法:
每次递归返回的都是值5的地址( return newHead;),就不用再找个变量记载了。链表指向的改变 由触底的递归返回来的值head 来指向head->next->next.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
方法三是无限头插法;**