2023每日刷题(二十八)
Leetcode—67.二进制求和
实现代码
void reverse(char *a, int len) {
for(int i = 0; i < len / 2; i++) {
char tmp = a[i];
a[i] = a[len - 1 - i];
a[len - 1 - i] = tmp;
}
}
char* addBinary(char* a, char* b) {
int len1 = strlen(a);
int len2 = strlen(b);
reverse(a, len1);
reverse(b, len2);
int maxn = len1 > len2 ? len1: len2;
char *ans = (char *)malloc(sizeof(char) * (maxn + 2));
int carry = 0;
int i = 0, j = 0;
int k = 0;
while(i < len1 && j < len2) {
int tmp = a[i++] - '0' + b[j++] - '0' + carry;
ans[k++] = tmp % 2 + '0';
carry = tmp / 2;
}
while(i < len1) {
int tmp = a[i++] - '0' + carry;
ans[k++] = tmp % 2 + '0';
carry = tmp / 2;
}
while(j < len2) {
int tmp = b[j++] - '0' + carry;
ans[k++] = tmp % 2 + '0';
carry = tmp / 2;
}
if(carry) {
ans[k++] = '1';
}
ans[k] = '\0';
reverse(ans, k);
return ans;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!