当前位置:网站首页>【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. 逆转操作需要熟记,而不是还要思考一会才能写
*/边栏推荐
- 【冷冻电镜】RELION4.0之subtomogram对位功能源码分析(自用)
- 模拟卷Leetcode【普通】081. 搜索旋转排序数组 II
- 游戏资产的革命
- 5g service interface and reference point
- 王树尧老师运筹学课程笔记 10 线性规划与单纯形法(关于检测数与退化的讨论)
- Share some tips for better code, smooth coding and improve efficiency
- 【技能积累】写邮件时的常用表达
- 量子机器学习中的安全性问题
- Salesforce中过滤器Filter使用的相对日期
- Teacher wangshuyao wrote the notes of operations research course 00 in the front
猜你喜欢

5g service interface and reference point

C language memory stack and heap usage

新同事写了几段小代码,把系统给搞崩了,被老板爆怼一顿!

竣达技术 | 适用于”日月元”品牌UPS微信云监控卡

Unity探索地块通路设计分析 & 流程+代码具体实现

SDN topology discovery principle

N2 interface of 5g control plane protocol

Shallow reading of condition object source code

IDEA找不到Database解决方法

Embedding understanding + code
随机推荐
Teacher wangshuyao's notes on operations research course 10 linear programming and simplex method (discussion on detection number and degradation)
崔雪婷老师最优化理论与方法课程笔记 00 写在前面
数据库持久化+JDBC数据库连接
CNN convolutional neural network
【冷冻电镜|论文阅读】A feature-guided, focused 3D signal permutation method for subtomogram averaging
猜数字//第一次使用生成随机数
Teacher Wu Enda's machine learning course notes 00 are written in the front
JMM memory model concept
【讲座笔记】如何在稀烂的数据中做深度学习?
吴恩达老师机器学习课程笔记 01 引言
没那么简单的单例模式
MySQL:当你CRUD时BufferPool中发生了什么?十张图就能说清楚
Simulation volume leetcode [ordinary] 172. Zero after factorial
二次元卡通渲染——进阶技巧
【冷冻电镜】RELION4.0 pipeline命令总结(自用)
Teacher Wu Enda machine learning course notes 01 introduction
微信小程序的反编译
Windows 上 php 7.4 连接 oracle 配置
How to write controller layer code gracefully?
2022年SQL经典面试题总结(带解析)