add: 220328-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-28 01:12:52 +08:00
parent 9021452a20
commit 05d81de019
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 20 additions and 1 deletions

19
cpp/2203/220328-CN.cpp Normal file
View File

@ -0,0 +1,19 @@
#include <iostream>
/**
* 693. Binary Number with Alternating Bits
* Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
*/
class Solution {
public:
static constexpr bool hasAlternatingBits(int n) {
unsigned x = unsigned(1 << (32 - __builtin_clz(n))) - 1;
return ((n ^ 0x55555555) & x) == x || ((n ^ 0xAAAAAAAA) & x) == x;
}
};
int main() {
std::printf("%s", Solution::hasAlternatingBits(33) ? "true" : "false");
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220327-CN.cpp)
ADD_EXECUTABLE(2203 220328-CN.cpp)