easy
0 views

Reverse Number

Given a number N, reverse its digits and print the result

Understand the Problem

Problem Statement

Number N is passed as the input. The program must reverse the digits of the number and print the reversed number as the output.

Constraints

  • 1 ≤ N ≤ 999,999,999
  • N is a positive integer
  • Reversed number should not have leading zeros

Examples

Example 1
Input
1234
Output
4321
Explanation

The digits of 1234 are reversed to form 4321

Example 2
Input
6500
Output
56
Explanation

The digits of 6500 are reversed to 0056, but leading zeros are removed, resulting in 56

Solution

#include <stdio.h>

int main() {
    int n, reversed = 0;
    
    scanf("%d", &n);
    
    while (n > 0) {
        reversed = reversed * 10 + n % 10;
        n = n / 10;
    }
    
    printf("%d", reversed);
    
    return 0;
}
Time:O(log N) - where log N is the number of digits in N
Space:O(1) - uses only a constant amount of extra space
Approach:

1. Read the input number N
2. Initialize reversed to 0
3. While N > 0:
    a. Multiply reversed by 10 and add the last digit (N % 10)
    b. Remove the last digit from N (N = N / 10)
4. Print the reversed number

The division operator / in C performs integer division, automatically removing the last digit in each iteration.

Visual Explanation

Loading diagram...