Created
November 22, 2012 08:49
-
-
Save juanfal/4130053 to your computer and use it in GitHub Desktop.
Counting 1s in a binary number with one loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// konesinarow2.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. | |
// One loop only (boolean helped) | |
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
int N, k; | |
cout << "Enter n: "; | |
cin >> N; | |
cout << "Enter k: "; | |
cin >> k; | |
int n = N; | |
int cnt = 0; | |
bool lastisone = false; | |
while (n > 0 and cnt < k) { | |
if (n % 2 == 1) { | |
lastisone = true; | |
++cnt; | |
} else { | |
lastisone = false; | |
cnt = 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