a,b 为二进制位串
d:下一进位
c:当前进位
x:和的当前位
#include <iostream> #include <string> #include <sstream> using namespace std; int main(){ string a = "101"; string b = "11111"; string s; stringstream ss; int x, c, d; c = 0; while (a.size() > b.size()) b = "0" + b; while (a.size() < b.size()) a = "0" + a; cout << a << endl; cout << b << endl; for (int i = a.size() - 1; i >= 0; i--){ d = ((a[i] - ‘0‘) + (b[i] - ‘0‘) + c ) / 2; x = (a[i] - ‘0‘) + (b[i] - ‘0‘) + c - 2 * d; ss << x; c = d; } ss << c; ss >> s; for (int i = s.size() - 1; i >= 0; i--) cout << s[i]; return 0; }
时间: 2024-12-16 09:28:59