question: set bits
answer:
code is not copying properly, so i sent the main part of the code…could you please correct it
question: set bits
answer:
code is not copying properly, so i sent the main part of the code…could you please correct it
hello @aarijrab
class Solution
{
public:
int setBits(int N)
{
// Write Your Code here
unsigned int count=0;
for(int i=0;i<32;i++) {
int temp=N&(1<<i);
if(temp!=0) {
count++;
}
}
return count;
}
};
this should be ur code.
a) there is no need to divide n .
b) else part is not required
but what is wrong in my code…i did similar question…the logic is perfectly fine…could you please correct my code
the code i shared above is ur corrected code only.
this is the logic -> go to each bit and check wheter it is set of not. if it is set then simply increment the count.
for(int i=0;i<32;i++) { int temp=N&(1<<i);
for(int i=0;i<32;i++) { … i<…bro please explain the syntax… int temp=N&(1<<i); bro what does these lines mean
using this loop we are iterating to first 32 bit posiiton of given number.
N&(1<<i) this will give u zero if ith bit of given number is zero, otherwise it will return non zero number (2^i).
still if u r faccing any issue then i would suggest to watch bit manipulation plylist of ur course, everthing is covered there.
refer this article