Reverse a Number in C++

Video Tutorial
FREE
Reverse a number thumbnail
This video belongs to
Data Structures in C++ Course
13 modules
Certificate
Topics Covered

Overview

Reversing a number means rearranging the digits in reverse order, i.e., the last digit comes first, followed by the second last digit, and so on, and the first digit comes at the last. There are many methods to reverse a number using C++, as discussed below.

Algorithm to Reverse a Number in C++

Digit reversal involves rearranging the order of a number's digits so that the last digit occupies the first position, the second-to-last digit moves to the second position, and so on. When the digits are reversed, the resulting number reads the same whether you read it forward or backward.

For instance, if we have the number "num" as 76453, the reversed form of "num" is 35467, which is the same when read in either direction. The logic of reversing a number in C++ is very simple, we will use super basic arithmetic operators (×,÷,%,etc.\times, \div, \%, \text{etc.}).

Following are the steps to find the reverse of a number -

  • Let's say we need to reverse a number n.
  • Declare a variable to store the reversed number (say rev) and initialize it to 0.
  • Do the following until n>0n>0
    • Multiply rev by 10.
    • Find the modulus of n with 10, i.e. n % 10 and add it to rev.
    • Divide n by 10.
  • Print the reversed number i.e.  rev\text{ } rev.

reversing number in C++

Let's dry run this algorithm on a sample number. Let's try to reverse 3821 using the above logic.

  • As per our first step, we will define a number rev to store the reversed number.
  • Now, we will iterate while n, i.e., 3821, is greater than 0.
  • Iteration 1 -
    • Multiplying rev by 10.
    • Adding n%10=3821%10=1n\%10 = 3821\%10=1 to revrev.
    • Dividing nn by 10 i.e.i.e. 3821/103821/10 After iteration 1 we will have rev=1rev = 1 and n=382n=382.
  • Iteration 2 -
    • Multiplying rev by 10.
    • Adding n%10=382%10=2n\%10 = 382\%10=2 to revrev.
    • Dividing n by 10 i.e.i.e. 382/10382/10 After iteration 1 we will have rev=12rev = 12 and n=38n=38.
  • Iteration 3 -
    • Multiplying rev by 10.
    • Adding n%10=38%10=8n\%10 = 38\%10=8 to rev.
    • Dividing n by 10 i.e. 38/1038/10 After iteration 1 we will have rev=128rev = 128 and n=3n=3.
  • Iteration 4 -
    • Multiplying rev by 10.
    • Adding n%10=3%10=3n\%10 = 3\%10=3 to revrev.
    • Dividing nn by 10 i.e.i.e. 3/103/10 After iteration 1 we will have rev=1281rev = 1281 and n=0n=0.
  • Now we have n=0n=0, so that means rev now holds the reversed number, i.e., 1283, which is indeed the reversed number.

C++ Program to Reverse a Number

Code

Output

Complexity Analysis

Time Complexity: O(log(n))O(log(n)), where n is the input number.

Auxiliary Space: O(1)

Using while loop

Before going ahead with the program, let's first understand how the while loop works. One-liner to define the while loop would be While loop gets executed until the condition is matched.

The flow of the while loop is like this -

  • While loop first checks the condition.
  • If the condition is true, the statements written inside it get executed.
  • If the condition is false, the loop will be terminated, and statements written outside the loop will start executing.

So, to reverse a number using a while loop, we will use the condition n0n \neq 0 and do the steps as explained in the previous section.

Output-

Explanation -

The while loop gets executed till the condition n0n\neq 0 evaluates to true, and in each iteration, the value of n%10n\%10 is added to revrev, and the value of n is divided by 10. Please have a look at the underlying table to grasp the concept in detail -

nnn0n\neq 0n%10n\%10revrev
1234true40×10+4=40\times 10 + 4 = 4
123true34×10+3=434\times 10 + 3 = 43
12true243×10+2=43243\times 10 + 2 = 432
1true1432×10+1=4321432\times 10 + 1 = 4321
0falseloop terminated\text{loop terminated}

Using for loop

The program to reverse a number using for loop is almost similar to the program that uses a while loop.

With little modification to that program, we can reverse a number using for loop.

Output-

Using Recursion

The thing that we have implemented using the while loop can also be implemented using recursion. The steps involved in implementing the algorithm to reverse a number (say n) recursively are listed below -

  • Define a global variable storing the reversed number, rev.
  • Multiply rev by 10.
  • Find the rightmost digit, i.e., KaTeX parse error: Expected 'EOF', got '%' at position 2: n%̲10, and add it to rev.
  • Call the recursive function with the argument as n10\frac{n}{10}.

Output-

The recursion tree for the given input, i.e., 1234 is as follows -

The recursion tree

Using function

To reverse a number in C++ using functions, we need to define a function (say reverse), and in that function, we can put all the statements needed to reverse a number (already discussed in the previous sections).

The program uses a user-defined function reverse to reverse a number. It accepts a single number num as an argument and returns an integer, the required reversed number.

Output -

By converting the int to a string

A given number can also be reversed by transforming it to a string and then reversing it using the following inbuilt functions of C++.

  • to_string(n) - This function is used to convert an integer to a string; it accepts a single argument of integer type and returns a string.
  • reverse (low, high) - This function is used to reverse data structures like an array, strings, etc. It accepts two arguments (say low and high) that denote starting and ending indices of the range we want to reverse.

The steps involved in the algorithm are -

  • Convert the given number (say n) to a string (say str) using the to_string(n) function.
  • Then reversing str using the inbuilt reverse function.
  • Printing str, which now holds n in reversed form.

Output-

Without using a loop

If we want to reverse a number without a loop or any other inbuilt function, we should use the goto statement to achieve functionality that is offered by the While loop or the For loop.

We will define the label MAGIC inside all statements required to reverse a number. After all the statements, we will check if n is not equal to 0; if the condition evaluates to true, then we will use the goto statement to go back and repeat all statements, just like the while loop.

Let us have a look at the program for a better understanding.

Output-

Using class and object

We can also use class an object, an object-oriented feature of C++, to reverse a number. We need to define an instance of the class (object) and then use the member function to reverse the passed number.

We will define a class (say MAGIC) and a member function (say reverse) that will accept an integer as the argument and return an integer that is the reversed number. The statements written inside the reverse function will exactly be the same as in our previous programs.

Output-

Using Array

To reverse a number in C++ using the concept of arrays, we need to store the digit of the original number in the reversed order, and then we can print the numbers to get the reversed number.

The logic will be -

  • Declare an integer array say a of size 10, here we will assume that n<9999999999n<9999999999, so that number of digits in n is always less than or equal to 10.
  • Now store n mod 10n\ \text{mod}\ 10 at each index of a starting from 0 and divide n by 10 in each iteration`.
  • Print the values stored in array a.

Here is the code to reverse the number in C++ using arrays -

Output-

Conclusion

  • Reversing a number means re-arranging so that the last digit comes first and the first digit comes last.
  • While/For loop can be used to reverse the number efficiently.
  • Along with the loop(s), other ways exist to reverse a number, i.e., using goto statements, inbuilt string statements, etc.