Question: I was solving the following problem:
*Reverse the digits of an integer.* Now the code for the problem is straightforward. 

```
void reverse(int x){
   if(x < 0){
      cout << "-";
      x*=(-1);
   }

   while(x!=0){
      cout << x%10;
      x/=10;
   }
}

```

But the problem asked the answer to be returned as integer. So I was wondering is there any way the output stream can be redirected to an integer. I know I could redirect it to a string and then convert to integer. But is there any direct way?

Answer: 
Instead of using `cout` to directly display the result, try storing the result to a variable, say `rev` and return the result.

```
int reverse(int x)
{    
    bool neg = x < 0;
    int rev = 0;

    while (x != 0) {
        rev = (rev * 10) + (x % 10);
        x /= 10;
    }
    return neg ? -rev : rev;
}

```
Why not creating a function that returns int?

```
#include <cmath> // needed for pow()

int reverse(int x)
{    
  int y=0;
  int numDigits=0;
  int x2=x;

  // first count number of digits

  while(x2!=0){
  x2/=10;
  numDigits++;
  }

  // then do the reversion by adding up in reverse direction

  for(int i=0; i<numDigits; i++){
  y+=(x%10)*pow(10,numDigits-i-1);
  x/=10;
  }

  return y;
}

```