std::ispow2

来自cppreference.com
< cpp‎ | numeric
定义于头文件 <bit>
template< class T >
constexpr bool ispow2(T x) noexcept;
(C++20 起)

检查 x 是否为二的整数次幂。

此重载仅若 T 为无符号整数类型(即 unsigned charunsigned shortunsigned intunsigned longunsigned long long 或扩展无符号整数类型)才参与重载决议。

返回值

x 为二的整数次幂则为 true ;否则为 false


可能的实现

template <std::unsigned_integral T>
    requires !std::same_as<T, bool> && !std::same_as<T, char>
constexpr bool ispow2(T x) noexcept
{
    return x != 0 && (x & (x - 1)) == 0;
}

示例

#include <bit>
#include <iostream>
 
int main()
{
    std::cout << std::boolalpha;
    for (auto i = 0u; i < 10u; ++i) {
        std::cout << "ispow2(" << i << ") = " << std::ispow2(i) << '\n';
    }
}

输出:

ispow2(0) = false
ispow2(1) = true
ispow2(2) = true
ispow2(3) = false
ispow2(4) = true
ispow2(5) = false
ispow2(6) = false
ispow2(7) = false
ispow2(8) = true
ispow2(9) = false