add: 220110

This commit is contained in:
Lam Haoyin 2022-01-10 23:55:41 +08:00
parent 92df83cad9
commit 7c76021232
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 26 additions and 1 deletions

25
2201/220110.cpp Normal file
View File

@ -0,0 +1,25 @@
#include <string>
#include <iostream>
#include <random>
class Solution {
public:
static std::string addBinary(const std::string& a, const std::string& b) {
char* const ret = new char[std::max(a.length(), b.length()) + 2]{};
int cin = 0;
for (int pos = std::max(a.length(), b.length()), posA = a.length() - 1, posB = b.length() - 1; posA >= 0 || posB >= 0; --posA, --posB, --pos) {
ret[pos] = (((posA < 0 ? 0 : (a[posA] ^ 48)) + (posB < 0 ? 0 : (b[posB] ^ 48)) + cin) & 1) ^ 48;
cin = ((posA < 0 ? 0 : (a[posA] ^ 48)) + (posB < 0 ? 0 : (b[posB] ^ 48)) + cin) >> 1;
}
if (cin)
*ret = '1';
std::string r(*ret ? ret : (ret + 1));
delete[] ret;
return r;
}
};
int main() {
std::cout << Solution::addBinary("0", "1");
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2201)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2201 220110-CN.cpp)
ADD_EXECUTABLE(2201 220110.cpp)