reverse an integer

i want to make a var equals the revers of the digit's of another var .
suppose that we have two integers (x , y) .. x=123 we want to set y to be y=321 .
what should we do ??
closed account (SECMoG1T)
hey check this function i made

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
26
27
28
29
30
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>

template <typename T>
 T my_reverse(T val)
{
    std::stringstream ss; ss.clear();
    std::string temp;

    ss<<val; ss>>temp;
    std::reverse(temp.begin(),temp.end());

    ss.clear();
    ss<<temp; ss>>val;
    return val;
}

int main()
{
    int x=345556,y=my_reverse(x);
    std::string str("c++"), str1=my_reverse(str);///wont work well for strings with white 
                                                                          ///spaces
    std::cout<<x<<std::endl;
    std::cout<<y<<std::endl;
    std::cout<<str<<std::endl;
    std::cout<<str1<<std::endl;
}
Last edited on
how about this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# include <iostream>
using namespace std;

int main(){

int number, reverse=0;
cout<<"Input a Number and press enter to reverse:\t";
cin>> number;

    for(; number!=0;)
    {
    reverse=reverse*10;
    reverse=reverse+number%10;
    number=number/10;
    }
cout<<"New reversed number is:\t\t"<<reverse;
return 0;

}
ebucna approach would be simpliest possible if you only want to use integers. And do not want to separate number into individual digits.
didn't he say he just wanted integers?
Topic archived. No new replies allowed.