tags:

views:

344

answers:

4

hi , I have a method to convert dec to bin

QList<bool> widgetInput::decToBin(int number)
{
        int remainder;
        QList<bool> result;
        if(number <= 1) {
            result << number;
            return result;
        }

        remainder = number%2;
        decToBin(number >> 1);
        result << remainder;


}

but unfortunately this method only holds one element in list . but when I replace the "result << number" with "cout << number" it will work. could you please help me and let me know where is my exact problem?

regards.

+2  A: 

You're very close, but you will need to make one modification:

    remainder = number%2;
    result << remainder << decToBin(number >> 1);
    return result;

I'm not sure exactly how QList works, but the above is intended to append the result of decToBin() after the remainder in the result. You may need to modify this slightly to make it work.

The result will then contain the binary representation of the number, in "reverse" order (with the least significant bit in the first position of the list).

Greg Hewgill
A: 

QList<bool> result; is a local variable so there can be only values inserted in this method call. And it is only one.

There are few solutions:

  • Add QList like a method parameter and after that if will work fine
  • Or append returned value from recursive calls to your list

But these solutions have reverse order so you can choose what is better for you.

And by the way, you are missing return value at the end of the method. So compiler should announce a warning.

Gaim
+2  A: 

On each recursive step, you are creating a new QList result; which is local to that step, then inserting the remainder into it. You don't need recursion (and in general it should be avoided when iteration will do):

QList<bool> result;

while(number > 0) {
  result << number%2;
  number /=2;
}

// Edited to add: Just realized you would also have to reverse QList here.
//  Depends on it's interface.

return result;

or better yet, just use a standard container:

bitset<sizeof(int)*CHAR_BIT> bs(number);
Todd Gardner
+1  A: 

First of all why make it recursive?

As pointed by others, the result variable is local, so it "resets" every time the method is called.

Because computers are binary beasts, I'd change to something like this:

QList<bool> widgetInput::decToBin(int number) 
{ 
    QList<bool> result = new QList<bool>(); 
    while (number)
    {
       result.Add(number & 1);
       number = number >> 1;
    }
    return result;
}
Paulo Santos
QList<bool> result; will do. No need for the C# verbosity :)
Todd Gardner