0

How to reverse a number?

example : 571 ---> 175

16th Aug 2016, 6:47 AM
Zafirah Mohamed iqbal
Zafirah Mohamed iqbal - avatar
2 Answers
+ 5
You could take in the number as a string, and reverse it from there. Note that this will reverse literally any string, not just numbers: #include <iostream> #include <string> using namespace std; int main() { string num; int numLgth; cout << "Enter a number: "; getline(cin, num); numLgth = num.length(); for (int i = numLgth - 1; i >= 0; i--) cout << num.at(i); }
16th Aug 2016, 10:46 AM
Cohen Creber
Cohen Creber - avatar
+ 4
other way: #include <iostream> #include <string> #include <algorithm> using namespace std; int main(void) { int num; cin >> num; string tmp = to_string(num); reverse(tmp.begin(), tmp.end()); cout << tmp << endl; return 0; }
16th Aug 2016, 11:39 AM
kiwiyou
kiwiyou - avatar