reverse digits

which function must i use to write a number in reverse and if the number is 5600 must be 65 . .
Your own function:)

Also it is not clear what means "to write a number in reverse". Either you need only output the original number in the reverse order on the console or you need to get a new number that is equal to the reversed original number.
Last edited on
closed account (3qX21hU5)
First question is the number in a integer? If so there are a few ways to do this.

1) Would be to convert the integer to a string with a stringstream and then reverse the string using the reverse() function in the algorithm header.

Reverse() can be found here http://www.cplusplus.com/reference/algorithm/reverse/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>

using namespace std;

int main()
{
    int number;
    cin >> number;

    // This is our stringstream it will be used for converting int to string.
    stringstream convert;

    // This will hold the number in string form
    string stringNumber;
    
    // Use the stringstream to convert the int into a string

    // Use the reverse function on the stringForm of the number here.

    cout << stringNumber;

}


2) The second option would be to use just simple math to do it :).

Here is something to get you started with it.

X is a int and is the number you wish to convert
Y is a int and will hold the reverse of X

Hint: You will need a while loop.

1
2
3
y *= 10;
y += x % 10;
x /= 10;



Now if you don't have to use a integer to hold the number and you can use any type you wish, just use a string to hold it the number and call the reverse function on the string.
Last edited on
Topic archived. No new replies allowed.