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:
- Initialize a variable
reversedNumber
to zero. This variable will store the reversed digits. - Extract the last digit of the number using the modulus operator (
n % 10
). - Add the digit to
reversedNumber
after multiplyingreversedNumber
by 10 (to shift its digits left). - Remove the last digit from the original number by dividing it by 10 (
n = n / 10
). - Repeat steps 2-4 until the number becomes zero.
- 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 inN
.) - Space Complexity:
O(1)
– Using a couple of variables i.e., constant space.