I'm stuck. Can somebody help me with the algorithm to convert a decimal integer (0 - 1,000,000,000) to binary recursively? I know I'm going to %2 until it equals 0 or 1, but then what do I do?
I'm stuck. Can somebody help me with the algorithm to convert a decimal integer (0 - 1,000,000,000) to binary recursively? I know I'm going to %2 until it equals 0 or 1, but then what do I do?
Last edited by skanxalot; 01-26-2003 at 12:20 PM.
Code:#include <iostream> using namespace std; void dectobin(int x) { if (x != 0) { dectobin(x >> 1); } cout<< !!(x & 1) <<flush; } int main() { dectobin(5); }
Last edited by Cela; 01-26-2003 at 03:00 PM.
*Cela*
OK, you're reply didn't make much sense to me as I think I'm quite a bit behind you. I've just been learning recursion for a week now. This is what I know:
To find the binary of a decimal you do int division by 2 until it equals 1. Let's say I was doing the integer 9.
9 --- 1
4 --- 0
2 --- 0
1 --- 1
So the binary is 1001.
So for the recursive function my anchor or base is 1, right?
So I use this to call it again? Recursive_Function(number/2)
How then do I get the numbers off the stack to check for odd/even?
Okay, ultra simple without any bitwise operations. :-) What you do is recurse deeper as long as the number isn't 0, when it is you print the modulus of the number you have and return.
The equivalent, more or less :-), with loops is like thisCode:#include <iostream> using namespace std; void dectobin(int x) { if (x != 0) { dectobin(x / 2); } cout<< x % 2 <<flush; } int main() { dectobin(9); }
Code:#include <iostream> #include <vector> using namespace std; void printbin(int x) { vector<int> bin; while (x != 0) { bin.push_back(x % 2); x = x / 2; } for (vector<int>::size_type i = 0; i < bin.size(); i++) { cout<< bin[i] <<flush; } } int main() { printbin(9); }
*Cela*
Cheers, mate!