I do an exercise on Hackerrank:
Task
Given a base-10 integer,n
, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive1
's inn
's binary representation. When working with different bases, it is common to show the base as a subscript.Example
The binary representation of
125
is1111101
. In base2
, there are5
and1
consecutive ones in two groups. Print the maximum,5
.
My solution is: I create a stack, push binary converted to it, and then I put it into new string. But when I run in dev-C++, the output I receive is just special characters. Can you explain to me and let me know how to fix?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
stack<char>st;
int temp;
while(n!=0){
temp = n%2;
n=n/2;
st.push(temp);
}
string s;
while(st.empty() == false){
s = s + st.top();
st.pop();
}
cout << s; // I try input n=5 but output is :) :)
// Count the maximum number of consecutive 1's
int d=0;
int max=0;
for (int i=0; i<s.size(); i++){
if (s[i]=='1') d++;
if (s[i]=='0'){
if (d>max) {
max=d;
d=0;
}
else d=0;
}
}
cout << max;
return 0;
}