Reference : https://en.wikipedia.org/wiki/Bitwise_operation
Bitwise operation is fast and simple action. because it is directly supported by the processor.
On low-cost processors, bitwise operations are substantially faster than division, several times faster than multiplication, somtimes significantly faster than addition. (really??)
- Bitwise Operator
NOT(bitwise complement)
NOT 0111 -> 1000, NOT10101011 -> 01010100
AND ( & )
AND 0101 - 0011 -> 0001, AND0011 - 0010 -> 0010
OR ( | )
OR 0101 - 0011 -> 0111, OR 0010 - 1000 -> 1010
NOT ( ~ )
Not 0101 -> 1010
XOR ( ^ )
XOR 0010 - 1010 -> 1000, XOR 0101 - 0011 -> 0110
- Bit shifts
In these operations, the digits are moved (shifted) to the left or right.
In LeetCode, There is problem that bit operator solve problem easily and faster.
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n < 0)
{
return false;
}
else
{
return n && !(n & n-1);
}
}
};
'개념공부 > C, C++, IDE' 카테고리의 다른 글
2차원 Vector Sort 방법 (0) | 2023.08.10 |
---|---|
[C언어] 변수의 유효 범위 (variable scope) (0) | 2023.07.03 |
[C++ STL] unordered_map (0) | 2023.01.16 |
[C++ STL] map (0) | 2023.01.16 |
[LeetCode] 1. Two Sum (1) | 2023.01.09 |