英文:
what is "&-" mean in c++
问题
I have never seen this symbol before in c++, how does it work?
这是C++中的代码片段,下面是其翻译:
#include <iostream>
#include <vector>
using namespace std;
void print(int i){
vector<int> a;
while (i){
a.push_back(i%2);
i/=2;
}
for (int i=a.size()-1; i>=0; i--)
cout<<a[i];
}
int main() {
for (int i=1000; i>0; i-=(i&-i)){
cout<<i<<' '<<int(i&i)<<' '<<int(i&-i)<<' ';
print(i); cout<<' '; print(int(i&-i));
cout<<'\n';
}
cout<<'\n';
for (int i=5; i<=1000; i+=(i&-i)){
cout<<i<<' '<<int(i&-i)<<' ';
print(i); cout<<' '; print(int(i&-i));
cout<<'\n';
}
return 0;
}
它的运行结果如下:
- 1000 1000 8 1111101000 1000
- 992 992 32 1111100000 100000
- 960 960 64 1111000000 1000000
- 896 896 128 1110000000 10000000
- 768 768 256 1100000000 100000000
- 512 512 512 1000000000 1000000000
- 5 1 101 1
- 6 2 110 10
- 8 8 1000 1000
- 16 16 10000 10000
- 32 32 100000 100000
- 64 64 1000000 1000000
- 128 128 10000000 10000000
- 256 256 100000000 100000000
- 512 512 1000000000 1000000000
英文:
I have never seen this symbol before in c++, how does it work?
#include <iostream>
#include <vector>
using namespace std;
void print(int i){
vector <int> a;
while (i){
a.push_back(i%2);
i/=2;
}
for (int i=a.size()-1; i>=0; i--)
cout<<a[i];
}
int main() {
for (int i=1000; i>0; i-=(i&-i)){
cout<<i<<' '<<int(i&i)<<' '<<int(i&-i)<<' ';
print(i); cout<<' '; print(int(i&-i));
cout<<'\n';
}
cout<<'\n';
for (int i=5; i<=1000; i+=(i&-i)){
cout<<i<<' '<<int(i&-i)<<' ';
print(i); cout<<' '; print(int(i&-i));
cout<<'\n';
}
return 0;
and it result
- 1000 1000 8 1111101000 1000
- 992 992 32 1111100000 100000
- 960 960 64 1111000000 1000000
- 896 896 128 1110000000 10000000
- 768 768 256 1100000000 100000000
- 512 512 512 1000000000 1000000000
- 5 1 101 1
- 6 2 110 10
- 8 8 1000 1000
- 16 16 10000 10000
- 32 32 100000 100000
- 64 64 1000000 1000000
- 128 128 10000000 10000000
- 256 256 100000000 100000000
- 512 512 1000000000 1000000000
答案1
得分: 3
这个表达应该被理解为 i & (-i)
。这是一种获取整数 i
中最低有效位的值的"技巧"。
英文:
The expression should be read as i & (-i)
. This is a "hack" to get the value of the least significant set bit in i
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论