C++ Exercises: Reverse the digits of a given integer
C++ Math: Exercise-3 with Solution
Write a C++ program to reverse the digits of a given integer.
Sample Input: 4
Sample Output: 4
Sample Input: 123
Sample Output: 321
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
int reverse_int(int x) {
int res = 0;
while(x != 0)
{
int pop = x % 10;
x = x / 10;
int candidate = res * 10 + pop;
if (candidate / 10 != res)
{
return 0;
}
res = candidate;
}
return res;
}
int main() {
cout << "Reverse of 4 is " << reverse_int(4) << endl;
cout << "Reverse of 123 is " << reverse_int(123) << endl;
cout << "Reverse of 208478933 is " << reverse_int(208478933) << endl;
cout << "Reverse of -73634 is " << reverse_int(-73634) << endl;
return 0;
}
Sample Output:
Reverse of 4 is 4 Reverse of 123 is 321 Reverse of 208478933 is 339874802 Reverse of -73634 is -43637
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to check the additive persistence of a given number.
Next: Write a C++ program to divide two integers (dividend and divisor) without using multiplication, division and mod operator.
What is the difficulty level of this exercise?