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 to0
. - Use a loop to extract the last digit of
N
usingN%10
, add it toreversedNumber
, and then remove the last digit fromN
using integer divisionN//10
. - Continue until
N
becomes0
.
- Initialize a variable
- 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 to7-digit
numbers efficiently.
Complexity:
- Time Complexity:
O(D)
whereD
is the number of digits inN
. Reversing each number runs in linear time relative to the number of digits. - Space Complexity:
O(1)
for the mathematical approach orO(D)
for the string approach.