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
reversedNumberto store the reversed result, initially set to0. - Use a loop to extract the last digit of
NusingN%10, add it toreversedNumber, and then remove the last digit fromNusing integer divisionN//10. - Continue until
Nbecomes0.
- 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-digitnumbers efficiently.
Complexity:
- Time Complexity:
O(D)whereDis 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.