当前位置:网站首页>【C语言刷LeetCode】67. 二进制求和(E)
【C语言刷LeetCode】67. 二进制求和(E)
2022-07-29 05:53:00 【kinbo88】
【
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
提示:
每个字符串仅由字符 '0' 或 '1' 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前导零。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/add-binary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
】
一道简单题,居然代码写了有一会,太菜了
1. 申请字符数组而不是int数组
2. 运算前需要-'0',运算后需要+'0'
3. 当a[i]+b[i]这种需要减两次'0'
4. 申请的长度 len + 2,记得初始化
5. 逆转操作需要熟记,而不是还要思考一会才能写
char * addBinary(char * a, char * b){
int lena = strlen(a);
int lenb = strlen(b);
int i, j;
int idx = 0;
int len = fmax(lena, lenb);
char *retarr = malloc(sizeof(char) *(len + 2));
int idxtmp = 0;
int flag = 0;
memset(retarr, 0, sizeof(char) *(len + 2));
i = lena - 1;
j = lenb - 1;
while (i >= 0 || j >= 0) {
if (i >= 0 && j < 0) {
idxtmp = a[i] - '0';
i--;
} else if (i < 0 && j >= 0) {
idxtmp = b[j] - '0';
j--;
} else if (i >= 0 && j >= 0){
idxtmp = a[i] + b[j] - '0' -'0';
i--;
j--;
}
idxtmp = idxtmp + flag;
flag = idxtmp / 2;
retarr[idx++] = idxtmp % 2 + '0';
}
if (flag != 0) {
retarr[idx++] = flag + '0';
}
i = 0; // 逆序
j = idx - 1;
while (i < j) {
char tmp = retarr[i];
retarr[i] = retarr[j];
retarr[j] = tmp;
i++;
j--;
}
return retarr;
}
/*
一道简单题,居然代码写了有一会,菜
1. 申请字符数组而不是int数组
2. 运算前需要-'0',运算后需要+'0'
3. 当a[i]+b[i]这种需要减两次'0'
4. 申请的长度 len + 2,记得初始化
5. 逆转操作需要熟记,而不是还要思考一会才能写
*/边栏推荐
- 数据库使用psql及jdbc进行远程连接,不定时自动断开的解决办法
- 【冷冻电镜】Relion4.0——subtomogram教程
- 模拟卷Leetcode【普通】081. 搜索旋转排序数组 II
- 微信小程序的反编译
- 吴恩达老师机器学习课程笔记 03 线性代数回顾
- Invalid access control
- Thread synchronization - producers and consumers, tortoise and rabbit race, dual thread printing
- IO流 - File - properties
- Talk about tcp/ip protocol? And the role of each layer?
- MySql基础知识(高频面试题)
猜你喜欢
随机推荐
Security in quantum machine learning
【技能积累】写邮件时的常用表达
mysql查询区分大小写
2022年SQL经典面试题总结(带解析)
Invalid access control
王树尧老师运筹学课程笔记 06 线性规划与单纯形法(几何意义)
SSH免密登录-两台虚拟机建立免密通道 双向信任
Embedding understanding + code
vim文本编辑器的一些使用小技巧
新同事写了几段小代码,把系统给搞崩了,被老板爆怼一顿!
2D cartoon rendering - advanced skills
Relative date used by filter in salesforce
Shallow reading of condition object source code
Teacher wangshuyao's notes on operations research course 10 linear programming and simplex method (discussion on detection number and degradation)
王树尧老师运筹学课程笔记 10 线性规划与单纯形法(关于检测数与退化的讨论)
Shallow reading of shared lock source code of abstractqueuedsynchronizer (AQS)
5g service interface and reference point
Salesforce中过滤器Filter使用的相对日期
数据库使用psql及jdbc进行远程连接,不定时自动断开的解决办法
Teacher Wu Enda machine learning course notes 01 introduction









