I created two functions that accept a decimal number and return the binary representation of that number. I chose a simple way to do this by concatenating on 1's and 0's to a string after some simple math. I created a iterative and recursive method to do this. Then I timed the two methods with a timer class my teacher gave me. It turned out that my recursive method was about twice as fast compared to my iterative method. Why would this be the case?
string CConversion::decimalToBinaryIterative(int num)
{
string ss;
while(num > 0)
{
if (num%2 != 0)
{
ss = '1' + ss;
}
else
{
ss = '0' + ss;
}
num=num/2;
}
return ss;
}
string CConversion::decimalToBinaryRecursive(int num)
{
if(num <= 0)
{
return "";
}
else
{
if (num%2 != 0)
{
return decimalToBinaryRecursive(num/2) + '1';
}
else
{
return decimalToBinaryRecursive(num/2) + '0';
}
}
}
Appending a character to a std::string
is cheaper than pre-pending one, because appending can be done without copying the string if string's capacity permits you to do so.
Prepending, however, always requires a copy of the entire string.
If you change your iterative code to this
string ss;
while(num > 0)
{
if (num%2 != 0)
{
ss = ss + '1';
}
else
{
ss = ss + '0';
}
num=num/2;
}
return string(ss.rbegin(), ss.rend());
the timing should be nearly the same, or the iterative should become narrowly faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With