Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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:

Flowchart: Reverse the digits of a given integer.

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?