利用或操作 | 和空格将英文字符转换为小写

('a' | ' ') = 'a'
('A' | ' ') = 'a'

利用与操作 & 和下划线将英文字符转换为大写

('b' & '_') = 'B'
('B' & '_') = 'B'

利用异或操作 ^ 和空格进行英文字符大小写互换

('d' ^ ' ') = 'D'
('D' ^ ' ') = 'd'

ASCII 编码 字符其实就是数字 恰巧这些字符对应的数字通过位运算就能得到正确的结果

判断两个数是否异号

int x = -1, y = 2;
bool f = ((x ^ y) < 0); // true

int x = 3, y = 2;
bool f = ((x ^ y) < 0); // false

n&(n-1) 消除数字 n 二进制表示中最后一个 1

Untitled

n - 1 一定可以消除最后一个 1,同时把其后的 0 都变成 1,这样再和 n 做一次 & 运算,就可以仅仅把最后一个 1 变成 0 了

191. Number of 1 Bits

aka. Hamming weight

Input: n = 00000000000000000000000000001011 Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

循环不断消除 1 同时计数直到 n 为 0

int hammingWeight(int n) {
	int res = 0;
	while (n != 0) {
		n = n & (n - 1);
		res++;
	}
	return res;
}