class Solution { public: string addBinary(string a, string b) { reverse(a.begin(),a.end()); reverse(b.begin(),b.end()); string c = ""; int carry =0; int i = 0; int j = 0; while(i<a.size()&&j<b.size()){ int sum = carry; sum+=a.at(i) - '0'; cout<<a.at(i)<<b.at(j)<<endl; sum+=b.at(j) - '0'; carry = sum/2; c+=to_string((sum%2)); i++;j++; } while(i<a.size()){ int sum = carry+ a.at(i++) - '0'; carry = sum/2; c+=to_string(sum%2); } while(j<b.size()){ int sum = carry+ b.at(j++) - '0'; carry = sum/2; c+=to_string(sum%2); } if(carry==1){ c+=to_string(carry); } reverse(c.begin(),c.end()); return c; } }; 这段代码里面 sum+=a.at(i) - '0';这个部分为什么要减去一个0字符
时间: 2024-02-14 08:28:45 浏览: 19
在C++中,字符的ASCII码是以整数形式表示的。当我们执行`a.at(i) - '0'`时,实际上是将字符a.at(i)的ASCII码值减去字符'0'的ASCII码值。这样做的目的是将字符转换为对应的数字。
在ASCII码表中,字符'0'的ASCII码值为48,而字符'1'的ASCII码值为49,以此类推,字符'9'的ASCII码值为57。通过将字符'a.at(i)'的ASCII码值减去字符'0'的ASCII码值,我们可以获得相应的数字。
例如,当a.at(i)为字符'1'时,'1'的ASCII码值是49,而'0'的ASCII码值是48。所以执行`a.at(i) - '0'`结果为1,得到了数字1。
这样做是为了方便进行字符与数字之间的转换,在这段代码中用于将二进制字符串中的字符转换为对应的数字进行计算。
相关问题
Write a program to reverse a string without using theandfunctions defined in the string.h library.
Sure, here's a program written in C to reverse a string without using any predefined functions from string.h library:
```
#include<stdio.h>
void reverseString(char str[]);
int main()
{
char str[100];
printf("Enter a string: ");
scanf("%s", str);
reverseString(str);
printf("Reversed string is: %s", str);
return 0;
}
void reverseString(char str[])
{
int length = 0;
// Calculate the length of the string
while (str[length] != '\0')
{
length++;
}
// Swap characters from beginning and end
for (int i = 0; i < length / 2; i++)
{
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}
```
In this program, we first take input from the user and pass it to the `reverseString()` function. Inside this function, we calculate the length of the string by iterating through it till we find the null character `'\0'`. Then, we swap the first character with the last one, second with second last one, and so on till we reach the middle of the string. Finally, we print the reversed string.
string.reverse
引用[2]中的代码示例展示了如何反转字符串。在这个示例中,使用了一个名为`reverseString`的函数来实现字符串的反转。该函数接受三个参数:原始字符串`s`、反转起始位置`start`和反转结束位置`end`。函数内部将字符串转换为字符数组,并通过交换数组中的元素来实现反转。最后,将反转后的字符数组转换回字符串并返回。你可以根据需要调用这个函数来实现字符串的反转。