Naf*_*Kay 45 java binary bit-manipulation bit bitwise-operators
我必须以整数的二进制表示形式翻转所有位.鉴于:
10101
Run Code Online (Sandbox Code Playgroud)
输出应该是
01010
Run Code Online (Sandbox Code Playgroud)
与整数一起使用时,实现此操作的按位运算符是什么?例如,如果我正在写一个类似的方法int flipBits(int n);,身体会发生什么?我只需要翻转数字中已经存在的内容,而不是整数中的所有32位.
Geo*_*rge 25
只需使用按位非运算符~.
int flipBits(int n) {
return ~n;
}
Run Code Online (Sandbox Code Playgroud)
要使用k个最低有效位,请将其转换为右掩码.
(我假设你至少需要1位,这就是掩码从1开始的原因)
int flipBits(int n, int k) {
int mask = 1;
for (int i = 1; i < k; ++i)
mask |= mask << 1;
return ~n & mask;
}
Run Code Online (Sandbox Code Playgroud)
正如LưuVĩnhPhúc所建议的那样,人们可以创建遮罩(1 << k) - 1而不是使用循环.
int flipBits2(int n, int k) {
int mask = (1 << k) - 1;
return ~n & mask;
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 13
有许多方法可以使用操作翻转所有位
x = ~x; // has been mentioned and the most obvious solution.
x = -x - 1; or x = -1 * (x + 1);
x ^= -1; or x = x ^ ~0;
Run Code Online (Sandbox Code Playgroud)
小智 5
更快更简单的解决方案:
/* inverts all bits of n, with a binary length of the return equal to the length of n
k is the number of bits in n, eg k=(int)Math.floor(Math.log(n)/Math.log(2))+1
if n is a BigInteger : k= n.bitLength();
*/
int flipBits2(int n, int k) {
int mask = (1 << k) - 1;
return n ^ mask;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83381 次 |
| 最近记录: |