Reverse digits of a number

Problem Statement: Given an integer. Write a program to reverse digits of a number.

Examples:

Example 1:
Input: N = 472
Output: 274
Explanation: Reading the number from back to front, we see that the output should be 274

Example 2:
Input: N = 470
Output: 74
Explanation: Reading the number from back to front, we get 074. For an integer with no decimals, we know that leading zeros have no significance and therefore our answer should be 74

Solution:

DisclaimerDon’t jump directly to the solution, try it out yourself first.

Intuition: Let’s say we have a three-digit number. Observe that we need to make the ten’s digit is the hundred’s digit and vice versa. Can we implement this by extracting the individual digits?

Approach:

  • Initialize our result as 0. We then start extracting digits one by one
  • For every digit extracted we store it in our result as res=res*10+d
  • Divide the number by 10 and repeat the process. Here’s a quick demonstration of the same

Code:

C++ Code

#include<bits/stdc++.h>
using namespace std;
int Rev(int n)
{
    int d,rev=0;
    while(n!=0)
    {
        d=n%10;
        rev=rev*10+d;
        n=n/10;
    }
    
    return rev;
}
int main()
{
    int n = 472;
    cout<<"The reverse of the given number is: "<<Rev(n);
    return 0;
}

Output:

The reverse of the given number is: 274

Time Complexity: O(log N)

Space Complexity: O(1)

Java Code

import java.io.*;
class Test
{
static private int Rev(int n)
{
	int d;
	int rev = 0;
	while (n != 0)
	{
		d = n % 10;
		rev = rev * 10 + d;
		n = n / 10;
	}

	return rev;
}
public static void main(String[] args)
{
	int n = 472;
	System.out.print("The reverse of the given number is: "+Rev(n));
}
}

Output:

The reverse of the given number is: 274

Time Complexity: O(log N)

Space Complexity: O(1)

Special thanks to Naman Daga for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article