diff --git a/cpp/2203/220328-CN.cpp b/cpp/2203/220328-CN.cpp new file mode 100644 index 0000000..a48c88a --- /dev/null +++ b/cpp/2203/220328-CN.cpp @@ -0,0 +1,19 @@ +#include + +/** + * 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; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index b361f53..9a683f4 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220327-CN.cpp) +ADD_EXECUTABLE(2203 220328-CN.cpp)