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;
}

```
You can convert it to a string and go backwards and send it to a stringstream.

```
std::stringstream s;

std::string s = std::to_string(x);
for (std::string::reverse_iterator rit = s.rbegin(); rit != s.rend(); ++rit) {
    std::cout << *rit;
    ss << *rit;
}
std::cout << std::endl;
return stoi(ss.str());

```

Add

```
#include <sstream>

```

I ran the int- and string-version 2.5 mill. times in a loop and the string-version is twice as fast on my macbook pro 2012. 1.2 secs. vs 2.4 secs. Something to consider using strings even though it may be seldom used.

Update:

Another SO [answer](https://stackoverflow.com/questions/24372480/reverse-string-c-using-char-array) suggests std::reverse and when I updated the code to

```
auto s = std::to_string(x);
std::reverse(s.begin(), s.end());
return stoi(s);

```

it used 0.8 secs., three times faster than swapping digits.