b******g 发帖数: 1721 | 1 我看到这个问题1337在下面链接:
http://www.leetcode.com/2011/08/reverse-bits.html#comment-4958
我看不懂下面这个:
if (lo ^ hi) {
x ^= ((1U << i) | (1U << j));
就是说如果lo位置的bit 和 hi 位置的bit不一样,就switch between them or
reverse each one. 我不懂的是
x ^= ((1U << i) | (1U << j));
如何做到的?
多谢。
如果1337网友看到,只是好奇你的网站为啥是1337? |
b*******a 发帖数: 68 | 2 我看到这个问题1337在下面链接:
http://www.leetcode.com/2011/08/reverse-bits.html#comment-4958
我看不懂下面这个:
if (lo ^ hi) {
x ^= ((1U << i) | (1U << j));
就是说如果lo位置的bit 和 hi 位置的bit不一样,就switch between them or
reverse each one. 我不懂的是
x ^= ((1U << i) | (1U << j));
如何做到的?
==> swap these two bits when they are different, meaning flip 0 -> 1, or
flip 1 -> 0, this can be done by XOR 1:
0 ^ 1 = 1
1 ^ 1 = 0
i.e., XOR 1 will flip the original bit |
i**********e 发帖数: 1145 | 3 x ^= ((1U << i) | (1U << j));
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
1 ^ 1 = 0
所以如果要 toggle 第 ith bit ,就直接
x = x ^ (1 << i);
要 toggle ith and jth bit:
x = x ^ (1 << i);
x = x ^ (1 << j);
把以上两行简写,就是:
x ^= ((1U << i) | (1U << j));
【在 b******g 的大作中提到】 : 我看到这个问题1337在下面链接: : http://www.leetcode.com/2011/08/reverse-bits.html#comment-4958 : 我看不懂下面这个: : if (lo ^ hi) { : x ^= ((1U << i) | (1U << j)); : 就是说如果lo位置的bit 和 hi 位置的bit不一样,就switch between them or : reverse each one. 我不懂的是 : x ^= ((1U << i) | (1U << j)); : 如何做到的? : 多谢。
|
i**********e 发帖数: 1145 | 4 1337 也就是 leet 的另外写法,是 elite 的意思。之前在未名注册的时候就想着用这
个 id,觉得挺酷。过后写博客的时候也顺其自然的也取同样名字了。 |
b******g 发帖数: 1721 | 5 我想通了。原以为 1U<
这个名字长见识,原先不知到有leet这种语言,是挺酷的。
【在 i**********e 的大作中提到】 : 1337 也就是 leet 的另外写法,是 elite 的意思。之前在未名注册的时候就想着用这 : 个 id,觉得挺酷。过后写博客的时候也顺其自然的也取同样名字了。
|