How do I reverse numbers or words to be backwords after I input those numbers or words.
Like say I input 5789, how do I make it come back out as 9875?
Any help would be much appreciated, thanks.
How do I reverse numbers or words to be backwords after I input those numbers or words.
Like say I input 5789, how do I make it come back out as 9875?
Any help would be much appreciated, thanks.
If it is stored as a string, you can use the reverse algorithm. If it is a number, you have to do some math to get each digit and then create a new number with the digits reversed, or you can convert it to a string, reverse it, and convert it back.
there's a simple way if you are strictly dealing with ints. i know
that the methods described already are more robust, but just to
point out that things can be done a little differently, try a loop like
this:
this reverses the order of the number, but any leading 0's areCode:while (num/10 != 0 || num%10 != 0) { printf ("%d", num%10); num = num/10; }
ignored. the looping condition allows the handling of 0's within
the number and prevents a loop that either finishes too early or
runs infinitely. limited functionality, but conveniently simple.
No No's:
fflush (stdin); gets (); void main ();
Goodies:
Example of fgets (); The FAQ, C/C++ Reference
My Gear:
OS - Windows XP
IDE - MS Visual C++ 2008 Express Edition
ASCII stupid question, get a stupid ANSI
I got it now, thanks guys.
i wrote a function to reverse a string, i used it in my base conversion algorithm, use this if you want:
don't ask about the random variable names / horrible code style.Code:std::string revstr(std::string str) { char tmp; int l = str.length(), l2 = l - 1, ong; for (ong = 0; ong < (l / 2); ong ++) { tmp = str[ong]; str[ong] = str[l2 - ong]; str[l2 - ong] = tmp; } return str; }
it's not too efficient but it's good enough for me.
Why would you use that to reverse a string when you can use reverse?Code:std::reverse(str.begin(), str.end());
No need to convert to a string first...Code:unsigned int reverseDecimalInteger(unsigned int x) { unsigned int result = 0; do { result = result * 10 + x % 10; x /= 10; } while (x > 0); return result; }
Last edited by iMalc; 02-05-2006 at 12:56 AM.
well mine was originally from C, and i didn't know that C++ had a reverse funtion...... i just used it when i ported one of my programs from C -> C++.