#include <iostream>
#include <algorithm>
int main()
{
std::string myStr;
int a;
std::cout << "Enter a number: ";
std::cin >> a;
myStr = std::to_string(a);
//reversing the string
std::string strMy = std::string(myStr.rbegin(), myStr.rend());
//as string has the leading zeroes!
std::cout << "As string: " << strMy << '\n';
//but as an int, obviously, has no leading zeroes!
int b = std::stoi(strMy);
std::cout << "As integer: " << b << '\n';
return 0;
}
Example 1
---------------
Enter a number: 1234
As string: 4321
As integer: 4321
Example 2
---------------
Enter a number: 1000
As string: 0001
As integer: 1
#include<iostream>
#include<conio>
#include<stdio>
void main()
{
int i=0,temp;
long num;
char rev[10];
cout<<"\n\nEnter Any Number - ";
cin>>num;
while(num!=0)
{
temp = num%10;
rev[i] = temp + 48;
num /= 10;
i++;
}
rev[i]='\0';
cout<<"\n\n\nReverse of the Number is - ";
puts(rev);
getch();
}
Enter Any Number - 1000
Reverse of the Number is - 0001
Enter Any Number - 253
Reverse of the Number is - 352
@Hiten Sharma: If the number is too long, which is possible, you will get out of bounds errors on your array. Instead, use someting like a std::string. Alternately, just do this (works not only for numbers):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string num;
std::cout << "Enter a number: ";
std::cin >> num;
std::reverse(num.begin(), num.end());
std::cout << "Reverse of number is: " << num << std::endl;
return 0;
}
Some other little things:
Don't use void main. Also, don't use conio.h and its either stdio.h or cstdio.
EDIT:
Just saw @Thumpers post, this is the same thing.
In ascii the number 48 is the character '0'.
To store the number 2 for example in a char variable you have to look up the decimal-representation for the character '2' = 50. Now if temp is 2 for example and you add 48 ⇒ 50 ⇒ '2'.
The code you provided is only applicable for the numbers which are perfect squares,cubes......so on.. of 10......What if the Number is something else like 1, 2001 or 589 ?
string whatever("Hello World!");
//display the string from end to beginning
for(string::const_iterator it = whatever.rbegin(); it != whatever.rend(); it++)
{
cout<< *it;
}
//or...
{ //limit the scope of x... you don't need to do this
int x = whatever.size();
do
{
x--;
cout<< whatever[x];
}
while(x > 0);
}
If you have any questions about this, you should ask.