find the digits

Printable View

• 01-05-2011
nimitzhunter
find the digits
I want to transform a number into a vector of it's digits. For example, 123 will be 1 2 3.
I came up with this code:

Code:

```void transform(const uint & x , deque<uint> & output) {   if ( x != 0 )     {       uint x_stripped = (x/10)*10;       uint digit = x - x_stripped;       output.push_front(digit);       transform(x_stripped / 10, output);     } }```
My question is, is there better way to do this? taking x and divide then multiply by 10 is a bit irksome for me.
• 01-05-2011
laserlight
You could try:
Code:

```void transform(const uint& x , deque<uint>& output) {     do     {         output.push_front(x % 10);         x /= 10;     }     while (x != 0); }```
• 01-05-2011
nimitzhunter
Quote:

Originally Posted by laserlight
You could try:
Code:

```void transform(const uint& x , deque<uint>& output) {     do     {         output.push_front(x % 10);         x /= 10;     }     while (x != 0); }```

laserlight, x/=10 wouldn't work because x is const. Maybe I could create a temp variable instead.
• 01-05-2011
laserlight
Quote:

Originally Posted by nimitzhunter
laserlight, x/=10 wouldn't work because x is const. Maybe I could create a temp variable instead.

Oh yeah, I did not notice that. Just change to use pass by value since passing by const reference is not likely to gain you anything here.
• 01-05-2011
nimitzhunter
Quote:

Originally Posted by laserlight
Oh yeah, I did not notice that. Just change to use pass by value since passing by const reference is not likely to gain you anything here.

Thanks alot for your help, laserlight. It works perfectly :-D.