将标准输出重定向为整数

Redirecting standard output to integer

本文关键字:整数 重定向 标准输出      更新时间:2023-10-16

我正在解决以下问题:反转整数的数字。现在,该问题的代码很简单。

void reverse(int x){
   if(x < 0){
      cout << "-";
      x*=(-1);
   }
   while(x!=0){
      cout << x%10;
      x/=10;
   }
}

但是问题要求将答案作为整数返回。所以我想知道是否有任何方法可以将输出流重定向到整数。我知道我可以将其重定向到字符串,然后转换为整数。但是有什么直接的方法吗?

与其使用 cout 直接显示结果,不如尝试将结果存储到变量中,例如 rev 并返回结果。

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

您可以使用 std::ostringstream ,保存缓冲区std::cout然后将其转换为 int:

void reverse(int x)
{
    std::ostringstream local_buffer;
    auto old_buff = std::cout.rdbuf(local_buffer.rdbuf()); // save pointer to std::cout buffer
    if(x < 0){
        std::cout << "-";
        x*=(-1);
    }
    while(x!=0){
        std::cout << x%10;
        x/=10;
    }
    std::cout.rdbuf(old_buff); // back to old buffer
    int rev = std::atoi(local_buffer.str().c_str());
    std::cout << "rev is: " << rev << "n";
}

科里鲁在线

为什么不创建一个返回 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;
}

您可以将其转换为字符串,然后向后将其发送到字符串流。

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());

#include <sstream>

我运行了int和string版本2.5工厂。 循环次数,字符串版本在我的MacBook Pro 2012上的速度是其两倍。 1.2秒与2.4秒 要考虑使用字符串的东西,即使它可能很少使用。

更新:

另一个 SO 答案建议 std::反向,当我将代码更新为

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

它使用0.8秒,比交换数字快三倍。