gpt4 book ai didi

c - 两个二进制数字串相加 - C

转载 作者:行者123 更新时间:2023-11-30 16:09:39 25 4
gpt4 key购买 nike

我知道互联网上有很多关于这个问题的信息,特别是 Stack - 但我仍然陷入困境。

给定两个二进制数字字符串 - 我们必须将它们的二进制和作为字符串返回。

实际上,我想我和这个人有同样的问题:Padding and adding binary strings in C

但我做了一些补充和改动,如下所示:

    // This function validates the two strings are really representing two binary number, and we keep the size of each
int isNum(const char* num, int* sizeOfNum) {
*sizeOfNum = 0;
while (*num != '\0') {
if (*num != '0' || *num != '1') {
return 0;
}
*sizeOfNum += 1;
}
return 1;
}

char* sumOfBinString(const char* num1, const char* num2) {

int* sizeOfNum1 = (int*)(malloc(sizeof(int));
int* sizeOfNum2 = (int*)(malloc(sizeof(int));

if (isNum(num1, sizeOfNum1) && isNum(num2, sizeOfNum2)) {

if (*sizeOfNum1 > *sizeOfNum2) {
int size = (*sizeOfNum1);
}
else {
int size = (*sizeOfNum2);
}
}

//This 'size' is actually the size of the longer binary number string, and plus one for the null-terminator
char *num1Copy = (char *)malloc((size+1) * sizeof(char));
char *num2Copy = (char *)malloc((size+1) * sizeof(char));

int i;
for(i = size; i >= 0; i--)
{
num1Copy[i] = '0';
num2Copy[i] = '0';
}

for (i = *sizeOfNum1; i >= 0; i--)
if (i == 0 && num1Copy[i]=='1') //Two's complement
num1Copy[i] = '1';
else
num1Copy[size - i] = num1[*sizeOfNum1-i];

for (i = *sizeOfNum2; i >= 0; i--)
if (i == 0 && num2Copy[i]=='1') //Two's complement
num2Copy[i] == '1';
else
num2Copy[size - i] = num2[*sizeOfNum2-i];
}

但我不知道如何从这里继续,因为在某些情况下进位可能会溢出,我需要“添加”这个数字作为 MSB。

有人可以帮助我从这里继续吗?

最佳答案

首先:

int* sizeOfNum1 = (int*)(malloc(sizeof(int));
int* sizeOfNum2 = (int*)(malloc(sizeof(int));

if (isNum(num1, sizeOfNum1) && isNum(num2, sizeOfNum2)) {

if (*sizeOfNum1 > *sizeOfNum2) {
int size = (*sizeOfNum1);
}
else {
int size = (*sizeOfNum2);
}
}

您不需要使用大小 bsc 的指针,这很容易忘记释放内存或陷入其他问题。您可以在 int 上执行此操作:

    int sizeOfNum1=0,sizeOfNum2=0;

if (isNum(num1, &sizeOfNum1) && isNum(num2, &sizeOfNum2)) { //if u add & isNum can modify sizeofNum1 by itself (You give address of variable to function)

if (sizeOfNum1 > sizeOfNum2) {
int size = sizeOfNum1;
}
else {
int size = sizeOfNum2;
}
}

对于加法背后的数学,就像在学校一样:

    111--- //carry line
1100
+ 10100
------
100000

在循环中,每个 sizeOfNum 有 2 个迭代器,当它达到 0 时,您只在输出中添加一个长度更长的迭代器(ofc 请记住,您需要始终检查进位,例如在 1100 迭代器将结束进位时)仍然是 1,所以你需要注意)这里有一些指南:

int i,j;    
i=(size==sizeOfNum1)?size:sizeOfNum2;
j=((i==sizeOfNum1)&&(i==size))?sizeOfNum2:sizeOfNum1;
for(;i>=0;i--,j--){
//here you are adding
}

关于c - 两个二进制数字串相加 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com