The most efficient way to reverse a number

后端 未结 10 758

I am looking for an efficient algorithm to reverse a number, e.g.

Input: 3456789

Output: 9876543

In C++ there are p

10条回答
  •  无人共我
    2021-01-13 05:03

    You may convert the number to string and then reverse the string with STL algorithms. Code below should work:

     long number = 123456789;
     stringstream ss;
     ss << number;
     string numberToStr = ss.str();
    
     std::reverse(numberToStr.begin(), numberToStr.end());
    
     cout << atol(numberToStr.c_str());
    

    You may need to include those relevant header files. I am not sure whether it is the most efficient way, but STL algorithms are generally very efficient.

提交回复
热议问题