+ 6
C++ from number to binary
The last digit of the binary number is always 1, even when it should be 0. How to solve that? https://code.sololearn.com/cGKLtvYrePal/?ref=app
6 Antworten
+ 5
I am beginner in c++ and I have no idea how to do that. 😅
+ 4
As mentioned "the algorithm prints the individual binary digits in reverse order", meaning, if the input is 128, then the output is
0000 0001
which is 1 instead of
1000 0000
This problem can be solved in a variety of ways, but it definitely reminds us of the elegant way a stack works. The stack is a sequential "last in first out" (LIFO) data structure in which the last stored (push) element (on top of the stack) is the first one to return (pop). As for number 128, with a slight change in the algorithm¹, the stack scheme would be like this when the first `while` block is done,
| 1 | <- top
| 0 |
| 0 |
| 0 |
| 0 |
| 0 |
| 0 |
| 0 | <- bottom
Now, it's ready for poping the stored digits one-by-one from the top to the bottom using the second `while` block,
while ( !st.empty() ) { // loop when the stack is not empty
cout << st.top(); // print the current top
st.pop(); // pop the last item and move the top one cell toward bottom
}
_____
¹
#include <iostream>
#include <stack>
using namespace std;
int main() {
int nr;
stack<int> st;
cin >> nr;
while ( nr > 0 ) {
if ( nr % 2 == 0 ) {
st.push( 0 );
}
else {
st.push( 1 );
}
nr /= 2;
}
while ( !st.empty() ) {
cout << st.top();
st.pop();
}
return 0;
}
+ 1
Its displayed in reverse, concat it to a string and print that string
+ 1
🍇 Alex Tusinean 💜, have you worked with arrays in JS?
It's almost the same, only the names differ.
#include <vector>
vector<int> v;
And then use the method push_back to add values in the end.
Finally: cout it backwards with a loop, again virtually the same as in JS.
Use the method size() instead of the attribute length to control the loop.
+ 1
this is another easy way
https://code.sololearn.com/clpzqZOs1szt/?ref=app