diff --git a/cpp/2204/220424-CN.cpp b/cpp/2204/220424-CN.cpp new file mode 100644 index 0000000..3eab1c9 --- /dev/null +++ b/cpp/2204/220424-CN.cpp @@ -0,0 +1,37 @@ +%:include +%:include + +/** + * 868. Binary Gap + * Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. + * Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3. + * + * Let's try something new today! + */ + +class Solution <% +public: + static int binaryGap(int n) <% + int ans = 0, current = 1; + while (not (n bitand 1)) <% + n >>= 1; + %> + if (n == 1) <% + return 0; + %> + for (; n; n >>= 1) <% + if (n bitand 1) <% + ans = std::max(ans, current); + current = 1; + %> else <% + ++current; + %> + %> + return ans; + %> +%>; + +int main() <% + std::cout << Solution::binaryGap(22); + return 0; +%> diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index dd42f12..f528297 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220423-CN.cpp) +ADD_EXECUTABLE(2204 220424-CN.cpp)