I need help with a C question with bitwise operations left
I need help with a C++ question with bitwise operations.
/*
* leftBitCount - returns count of number of consective 1\'s in
* left-hand (most significant) end of word.
* Examples: leftBitCount(-1) = 32, leftBitCount(0xFFF0F0F0) = 12
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 50
* Rating: 4
*/
It needs to take an int and return the value of the count of left bits.
int leftBitCount(int x) {
return ;
}
Solution
#include <iostream>
#include <string> // std::string
#include <bitset>
int leftBitCount(int x);
int main(int argc, char *argv[])
std::cout << leftBitCount(-1);
}
int leftBitCount(int x) {
int result=0; //initialise result to 0
std::bitset<32> bar (x); // converts int to binary array named bar in which leftmost bit is stored at bar[31]
for (int count=31; count >= 0; --count){ //runs a loop to count number of leftmost 1\'s in bar array
if(bar[count]==1){
result++; // each time we find 1 increase result by 1
}else{
break; // first time we encounter 0 in bar array we break the loop
}
}
return result;
}
