Skip to content

Commit

Permalink
Add getBinaryGap function
Browse files Browse the repository at this point in the history
  • Loading branch information
robosherpa committed Nov 15, 2021
1 parent 7bba108 commit 16352d0
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
13 changes: 13 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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
)

25 changes: 25 additions & 0 deletions src/binary_gap.cpp
Original file line number Diff line number Diff line change
@@ -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;
}
36 changes: 36 additions & 0 deletions tests/binary_gap_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include "src/binary_gap.cpp"
#include <gtest/gtest.h>
#include <thread>
#include <iostream>

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();
}

0 comments on commit 16352d0

Please sign in to comment.