Programming & Design
Question:
In C++, How should I write a function that takes in a number and outputs it in reverse order?
metalgearsolid
2011-02-08 21:39:10 UTC
Sorry, I just have programmers block today. What way do you recommend doing it yourself? pseudocode welcomed, actual code preferred. Thank you.
Note: By reverse order I mean like this,
input:
1234567
output
7654321
Three answers:
Light Cloud
2011-02-08 21:46:44 UTC
Both above posters suggest excellent methods (one numeric, one via string). Just for kicks, here's a recursive solution:
void reverse(int input) {
if (input < 10) { // if there's only one digit, we can just print this number and we're done
printf("%d", input);
return;
}
// Otherwise, we should print out the least significant digit first, which is input % 10
printf("%d", input % 10);
// Then, we should print out the rest of the number (i.e. input / 10) in reverse order.
// A recursive call can do this, because that is exactly what this function does
reverse(input / 10);
}
JoelKatz
2011-02-09 05:41:55 UTC
Peel the digits off the right of the input one by one and shift them onto the right of the output one by one, like this:
int rev(int in)
{
int out=0;
while(in>0)
{
out=(out*10)+(in%10);
in/=10;
};
return out;
}
Pearls Before Swine
2011-02-09 05:42:11 UTC
I would do these steps:
- Convert the number into a string using something like sprintf()
- Use a string function like strrev() to reverse the string
- Then output that string using printf(), or if you want first convert the string back to a number using something like atoi()
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...