Reversing a number

D

deanfamily11

I need to write a function that takes an integer as a parameter and then
returns it reversed (i.e. input: 45678, returned: 87654). Can anyone help?
 
A

Alf P. Steinbach

* deanfamily11:
I need to write a function that takes an integer as a parameter and then
returns it reversed (i.e. input: 45678, returned: 87654).

Of course, that problem pops up in all kinds of everyday situations.

Can anyone help?

Start by writing out the digits in right-to-left order, by using integer
division in a loop. Example: 45678/10 = 4567 when "/" denotes integer
division. And what do you get when you multiply the result by 10?


Follow-up set to [comp.programming].
 
S

Someonekicked

you can convert the inetger to a string, now a string is a just a vector,
you can reverse it easily, then you can convert back to integer.
 
M

Mike Wahler

deanfamily11 said:
I need to write a function that takes an integer as a parameter and then
returns it reversed (i.e. input: 45678, returned: 87654). Can anyone help?

#include <iostream>
#include <sstream>
#include <string>

int rev(int value)
{
std::stringstream ss;
ss << value;
std::string s(ss.str());
std::reverse(s.begin(), s.end());
ss.str(s);
int result(0);
ss >> result;
return result;
}

int main()
{
std::cout << rev(45678) << '\n';
return 0;
}

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top