Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created November 22, 2012 08:50
Show Gist options
  • Save juanfal/4130059 to your computer and use it in GitHub Desktop.
Save juanfal/4130059 to your computer and use it in GitHub Desktop.
Counting 1s in a binary number nested loops
// konesinarow.cpp
// juanfc 2012-06-24
// Design a program that reads from keyboard two natural numbers $k$ and
// $n$ and sends to the screen a message that indicates whether $n$ has
// got at least $k$ 1s (ones) straight without a break, or not. For example,
// if $k=3$ and $n=135$ the program should display ‘Yes’ since 135 as binary
// is ‘1000 0111’ that does have at least 3 ones in a row.
#include <iostream>
using namespace std;
int main()
{
int N, k;
cout << "Enter n: ";
cin >> N;
cout << "Enter k: ";
cin >> k;
int cnt = 0;
int n = N;
while (n > 0 and cnt < k) {
while (n % 2 == 1 and cnt < k) {
++cnt;
n /= 2;
}
if (cnt < k and n > 0) {
cnt = 0;
while (n > 0 and n % 2 == 0) {
n /= 2;
}
}
}
if (cnt >= k)
cout << "Yes, " << N << " has " << k << " 1s in a row" << endl;
else
cout << "No, " << N << " hasn't " << k << " 1s in a row" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment