By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,225 Members | 2,172 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,225 IT Pros & Developers. It's quick & easy.

Reversing a number

P: n/a
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?
Sep 11 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
* 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].
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Sep 11 '05 #2

P: n/a
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.
"deanfamily11" <de**********@verizon.net> wrote in message
news:N1OUe.879$R9.111@trnddc02...
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?

Sep 11 '05 #3

P: n/a

"deanfamily11" <de**********@verizon.net> wrote in message
news:N1OUe.879$R9.111@trnddc02...
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
Sep 11 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.