洛谷 U527608 8位二进制加法

本人写的第一个题目。

题目传送门


思路:

读入两个字符串(std::string)a、b,从最低位依次进行相加,a与b的和入栈t,如果最高位有进位,它(1)也进栈。最后依次输出栈中的每一个元素,栈起倒序输出的作用。

参考C++代码:

#include 
std::string a, b;
int s = 0;
std::stack t;
int main()
{
    std::cin >> a >> b;
    for (int i = 7; i >= 0; i--)
    {
        t.push(((a[i] - '0') + (b[i] - '0') + s) % 2);
        s = ((a[i] - '0') + (b[i] - '0') + s) / 2;
    }
    if (s == 1)
        t.push(1);
    while (!t.empty())
    {
        std::cout << t.top();
        t.pop();
    }
    return 0;
}

你可能感兴趣的:(算法)