![]() |
VOOZH | about |
In C++ 20, the std::has_single_bit function is a predefined function that is used to check if a given value is an integral power of two or not. This function is defined in the <bit> header file.
The std::has_single_bit() function works by checking whether a given integer has exactly one bit set to '1' in its binary representation because the numbers that are powers of two have only one bit set in their binary form. For example, 2 is 10 in binary, 4 is 100, 8 is 1000 and so on.
std::has_single_bit(num)This function accepts a single parameter:
The std::has_single_bit function return:
Input:
Num: 4
Output:
4 has a single bit set.
Explanation : Binary representation of 4 is 0100 which has exactly one set bit.
Therefore, 4 = 2^2 which is a integral power of two.
The below example demonstrates how we can use has_single_bit() function to check if a given value is an integral power of two in C++.
Output
16 has a single bit set.Time Complexity : O(1), function has_single_bit() is a constant-time operation
Auxilliary Space: O(1)
Note: The has_single_bit() function only works with unsigned integer types. Always make sure to provide unsigned integer as an input to this function. Failing to do so will result in a compiler error.