add: 220424-CN [cpp]

This commit is contained in:
eat-swap 2022-04-24 20:26:47 +08:00
parent 5d4af0d1f4
commit 31dc21bfa2
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 38 additions and 1 deletions

37
cpp/2204/220424-CN.cpp Normal file
View File

@ -0,0 +1,37 @@
%:include <iostream>
%:include <algorithm>
/**
* 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;
%>

View File

@ -3,4 +3,4 @@ PROJECT(2204)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2204 220423-CN.cpp) ADD_EXECUTABLE(2204 220424-CN.cpp)