FLOW007 - Editorial

Problem Link - Reverse The Number Practice Problem in 500 to 1000 difficulty problems

Problem Statement:

Given an Integer N, write a program to reverse it.

Approach:

Reverse the integer:

  • Use mathematical operations to reverse the digits of the integer:
    • Initialize a variable reversedNumber to store the reversed result, initially set to 0.
    • Use a loop to extract the last digit of N using N%10, add it to reversedNumber, and then remove the last digit from N using integer division N//10.
    • Continue until N becomes 0.
  • Alternatively, convert the integer to a string, reverse the string, and convert it back to an integer for simplicity.

Edge Cases:

  • Single-digit numbers: The reverse should be the number itself.
  • Numbers with trailing zeros (e.g., 2300): The reverse should remove leading zeros (e.g., 32).
  • Maximum constraint N=1,000,000: Ensure the program can handle up to 7-digit numbers efficiently.

Complexity:

  • Time Complexity: O(D) where D is the number of digits in N. Reversing each number runs in linear time relative to the number of digits.
  • Space Complexity: O(1) for the mathematical approach or O(D) for the string approach.