more tests

This commit is contained in:
2023-10-06 13:00:16 +02:00
parent a11d45d64e
commit 2a3417e95f
3 changed files with 106 additions and 10 deletions

58
codility/binarygap.cpp Normal file
View File

@@ -0,0 +1,58 @@
#include <cstdio>
#include <bitset>
#include <string>
#include <algorithm>
auto bin2str(int num) -> std::string {
constexpr std::size_t max_position = sizeof(int) * 8;
std::string str{};
for (std::size_t i = 0; i < max_position; ++i) {
str += (num & (1 << i)) ? '1' : '0';
if ((i + 1) % 8 == 0 && i < max_position - 1) str += "'";
}
std::reverse(std::begin(str), std::end(str));
return str;
}
int solution(int N) {
constexpr std::size_t max_position = sizeof(int) * 8;
std::size_t start = 0;
std::size_t end = 0;
std::size_t final_start = 0;
std::size_t final_end = 0;
for (std::size_t i = 0; i < max_position; ++i) {
bool const is_one_start = (N & (1 << i)) >> i;
if (is_one_start) {
start = i;
for (std::size_t j = start + 1; j < max_position; ++j) {
bool const is_one_end = (N & (1 << j)) >> j;
if (is_one_end) {
end = j;
break;
}
}
} else continue;
if (end - start > final_end - final_start) {
final_start = start;
final_end = end - 1;
}
}
std::intptr_t size = final_end - final_start;
if (size > 0) return size;
else return 0;
}
auto main() -> int {
int input = 32;
auto gap = solution(input);
std::printf("Input: %d, [%s]\n", input, bin2str(input).c_str());
std::printf("Gap: %d\n", gap);
std::printf("%s\n", bin2str(1 << 0).c_str());
std::printf("%s\n", bin2str(0x2&(1 << 0)).c_str());
return 0;
}