Reverse Number Program in C
The reverse of a number means reversing the order of digits of a number. In this article, we will learn how to reverse the digits of a number in C programming language. For example, if number num = 12548, the reverse of number num is 84521.
Algorithm to Reverse an Integer
Input: num (1) Initialize rev_num = 0 (2) Loop while num > 0 (a) Multiply rev_num by 10 and add remainder of num divide by 10 to rev_num rev_num = rev_num*10 + num%10; (b) Divide num by 10 (3) Return rev_num
C Program to Reverse an Integer
C
// C program to implement // the above approach #include <stdio.h> // Iterative function to // reverse digits of num int reverseDigits( int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code int main() { int num = 4562; printf ( "Reverse of is %d" , reverseDigits(num)); getchar (); return 0; } |
Reverse of no. is 2654
Complexity Analysis
Time Complexity: O(log(n)), where n is the input number.
Auxiliary Space: O(1)
Explanation
The above program takes an integer num as input. We use a while loop to iterate until the value of num becomes 0. Inside the loop, the last digit of num is extracted using the modulo operator (num % 10). This digit is then added to rev_num after multiplying it by 10, which means the existing digits of rev_num are shifted one place to the left.
The value of num is updated by dividing it by 10, (num = num / 10). This removes the last digit of num in each iteration, and terminates the loop when num becomes 0. rev_num is returned, which contains the reversed digits of the original number.
num = 4562 rev_num = 0 rev_num = rev_num *10 + num%10 = 2 num = num/10 = 456 rev_num = rev_num *10 + num%10 = 20 + 6 = 26 num = num/10 = 45 rev_num = rev_num *10 + num%10 = 260 + 5 = 265 num = num/10 = 4 rev_num = rev_num *10 + num%10 = 2650 + 4 = 2654 num = num/10 = 0
Contact Us