diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b3b7a0..ab6f605 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,6 +7,8 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) # Locate GTest find_package(GTest REQUIRED) +make_directory(build) + include_directories( ${PROJECT_BUILD_DIR} ${PROJECT_SOURCE_DIR} @@ -37,4 +39,15 @@ target_link_libraries( pthread ) +# Link executables +add_executable( + build/binaryGapTest + tests/binary_gap_test.cpp + ) + +target_link_libraries( + build/binaryGapTest + ${GTEST_LIBRARIES} + pthread + ) diff --git a/src/binary_gap.cpp b/src/binary_gap.cpp new file mode 100644 index 0000000..78d73bd --- /dev/null +++ b/src/binary_gap.cpp @@ -0,0 +1,25 @@ +int getBinaryGap(int N) +{ + auto max_gap = 0; + bool current_state = false; + bool last_state = false; + auto current_gap_length = 0; + while(N > 0) + { + current_state = N%2; + if (current_state == last_state) + { + current_gap_length++; + } + else + { + if (current_gap_length > max_gap) + { + max_gap = current_gap_length; + } + current_gap_length = 0; + } + N >>= 1; + } + return max_gap; +} \ No newline at end of file diff --git a/tests/binary_gap_test.cpp b/tests/binary_gap_test.cpp new file mode 100644 index 0000000..2858ad8 --- /dev/null +++ b/tests/binary_gap_test.cpp @@ -0,0 +1,36 @@ +#include "src/binary_gap.cpp" +#include +#include +#include + +TEST (BinaryGapAllOnes, Test1) +{ + uint8_t b = 0b11111111; + ASSERT_EQ(getBinaryGap(b), 0); +} + + +TEST (BinaryGapAllZeros, Test2) +{ + uint8_t b = 0b00000000; + ASSERT_EQ(getBinaryGap(b), 0); +} + +TEST (BinaryGap1, Test3) +{ + uint8_t b = 0b10001001; + ASSERT_EQ(getBinaryGap(b), 3); +} + +TEST (BinaryGap2, Test4) +{ + uint8_t b = 0b10000001; + ASSERT_EQ(getBinaryGap(b), 6); +} + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +