简体   繁体   中英

porting a c++ piece of code that does bit manipulation in python

int solution(vector <int> &nums){
    int cnt[30]={0};
int p[30];
for(int i=0,b=1;i<30;++i,b<<=1) p[i] = b;
for(int n: nums) {
  for(int i=0;i<30 and p[i]<=n;++i)
    if(n&p[i]) ++ cnt[i];
}
return *max_element(cnt, cnt+30);
 
}

How do we convert this piece of code to python? We tried implementing the above using two for loops in python but couldn't get there.

for i in range(30):
    for b in range(b/=2):

This is just setting p to [1, 2, 4, 8, 16.....] .

So p = [1 << i for i in range(30)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM