Program to Reverse a Number in C.

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

To reverse a number, we need to extract each digit of the given number from right to left and then construct the reversed number by adding the digits in the reverse order.

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;
}
Output:
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.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS