Given an integer number num containing n digits, we need to write a C program to reverse the given number.
Example:
Input: num = 1234 Output: 4321 Input: num = 45910 Output: 1954
Algorithm to Reverse a Number.
Below are the steps to follow:
Step 1: Take an integer num as input from the user.
Step 2: Initialize a variable reversedNum to 0.
Step 3: Repeat the following steps until num becomes 0:
- Extract the last digit of num using num % 10 and store it in a variable remainder.
- Append the remainder to the reversedNum by multiplying reversedNum by 10 and adding the remainder.
- Remove the last digit from num by dividing it by 10.
Step 4: The final value of reversedNum is the reversed number.
Program to Reverse an Integer.
Below is the C code implementation of the above algorithm to reverse any integer number.
//C program to reverse a number #include <stdio.h> int main() { int num, reversedNum = 0, remainder; printf("Enter an integer: "); scanf("%d", &num); while (num != 0) { // Extract the last digit remainder = num % 10; // Append the digit to the reversed number reversedNum = reversedNum * 10 + remainder; // Remove the last digit num /= 10; } printf("Reversed number: %d\n", reversedNum); return 0; }
Enter an integer: 1246
Reversed number: 6421
Time Complexity: O(log n) where n is the input number.
Space Complexity: O(1) as a constant amount of space is required to solve this problem.
No comments:
Post a Comment