我想取一个int作为输入,并返回第k位.
int getBit(int n, int k){
return kth bit in n;
}
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
Doo*_*nob 73
使用按位运算符:
int getBit(int n, int k) {
return (n >> k) & 1;
}
Run Code Online (Sandbox Code Playgroud)
说明(以位为单位):
n
100010101011101010 (example)
n >> 5
000001000101010111 (all bits are moved over 5 spots, therefore
& the bit you want is at the end)
000000000000000001 (0 means it will always be 0,
= 1 means that it will keep the old value)
1
Run Code Online (Sandbox Code Playgroud)
return (n >> k) & 1;
Run Code Online (Sandbox Code Playgroud)
在这里,n >> k将k-th位移到最不重要的位置,并& 1屏蔽掉其他所有内容.
| 归档时间: |
|
| 查看次数: |
33951 次 |
| 最近记录: |