![]() |
VOOZH | about |
Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean.
In Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True if the expression is False, and False if the expression is True. In the below example, we have used the logical not operator in Python. Here, the variable a is assigned the value True, and the variable b is assigned the inverse of a using the not operator. The output of the print statements shows that a is True, while b is False.
True False
Time Complexity: O(1)
Space Complexity: O(1)
Consider below programs that use the Logical Not (or !) operator on a boolean.
0 1 1 0
Time complexity: O(1)
Auxiliary space: O(1)
The bitwise not operator is used to invert the bits of an integer, including its sign bit, which changes the sign of the integer. In this example, we are using Btiwise Not ( or ~) operator. Code implementation is given below.
-2 -1
In this example, the variable a is assigned the value 5, and the variable b is assigned the inverse of a using the bitwise not operator. The output of the print statements shows that a is 5, while b is -6.
5 -6
Note that the bitwise not operator only works on integers, and not on Boolean values. Also, the bitwise not operator is different from the logical not operator, and should be used with caution.
"Logical not or !" is meant for boolean values and "bitwise not or ~" is for integers. Languages like C/C++ and python do auto promotion of boolean to integer type when an integer operator is applied. But Java doesn't do it.