Wednesday, October 12, 2016

Finding the number of consecutive 1s

Question is at link - 
Binary numbers

Code :
#include<iostream>
using namespace std;
int main(){
    long long int n;
    cin>>n;
    int count=0;
    while(n){
        n = (n&(n<<1));
        count++;
    }
    cout<<count;
    return 0;
}
Sol :
We shift the binary digits of the number using shift operator and AND it.

No comments:

Post a Comment

Search This Blog