位操作运算符

C++基本的位操作符有与、或、异或、取反、左移、右移这6种,它们的运算规则如下所示:

符号 描述 运算规则
& 两个位都为1时,结果才为1
| 两个位都为0时,结果才为0
^ 异或 两个位相同为0,相异为1
~ 取反 0变1,1变0
<< 左移 各二进位全部左移若干位,高位丢弃,低位补0
>> 右移 各二进位全部右移若干位,对无符号数,高位补0,有符号数,各编译器处理方法不一样,有的补符号位(算术右移),有的补0(逻辑右移)

Note:

  • 位操作只能用于整形数据,对float和double类型进行位操作会被编译器报错。
  • 位操作符的运算优先级比较低,因为尽量使用括号来确保运算顺序,否则很可能会得到莫明其妙的结果
  • 另外位操作还有一些复合操作符,如&=、|=、 ^=、<<=、>>=

位操作实战

476. Number Complement Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Example 1:

Input: 5

Output: 2

Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1

Output: 0

Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.
  3. This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/

题目来源:https://leetcode.com/problems/number-complement/

  1. class Solution {
  2. public:
  3. int findComplement(int num) {
  4. int tmp = num;
  5. int mask = 0;
  6. while (tmp)
  7. {
  8. mask = mask << 1;
  9. mask = mask | 1;
  10. tmp = tmp >> 1;
  11. }
  12. int result = (~num) & mask;
  13. return result;
  14. }
  15. };