Problem Statement

We are given an integer n. Return the integer formed by placing the digits of n in reverse order.

Examples

Example 1:

Input: n = 45
Output: 54
Example 2:

Input: 177
Output: 771
Example 3:

Input: 0
Output: 0

Approaches

1️⃣ Modulus and Division

Intuition:

To reverse the digits of a number, the idea is to extract each digit from the number and build a new number in reverse order.

Steps:

  1. Initialize a variablereversedNumber to zero. This variable will store the reversed digits.
  2. Extract the last digit of the number using the modulus operator (n % 10).
  3. Add the digit to reversedNumber after multiplying reversedNumber by 10 (to shift its digits left).
  4. Remove the last digit from the original number by dividing it by 10 (n = n / 10).
  5. Repeat steps 2-4 until the number becomes zero.
  6. The value of reversedNumber at the end will be the reversed number.

Code:

#include <iostream>

int reverseNumber(int n) {
    int reversedNumber = 0;
    
    while (n > 0) {
        int digit = n % 10;  // Extract the last digit
        reversedNumber = reversedNumber * 10 + digit;  // Add it to reversedNumber
        n = n / 10;  // Remove the last digit
    }
    
    return reversedNumber;
}

int main() {
    int n;
    std::cout << "Enter a number: ";
    std::cin >> n;

    int result = reverseNumber(n);
    std::cout << "Reversed number: " << result << std::endl;

    return 0;
}

Complexity Analysis:

  • Time Complexity:O(log10(N)) – In every iteration, N is divided by 10 (equivalent to the number of digits in N.)
  • Space Complexity:O(1) – Using a couple of variables i.e., constant space.