C: Reverse the digits

Read a whole number and print it with its digits reversed. Leading zeros of the result are dropped (1200 becomes 21), and a negative number stays negative.

What to build

A loop that takes one number apart and builds another.

Requirements

  • Read the number.
  • Print its digits in reverse, keeping any minus sign.

Input

One whole number between -100000000 and 100000000.

Output

The reversed number.

Constraints

The number is between -100000000 and 100000000.

Example

Input:

1234

Output:

4321

Why it works

% 10 gives the last digit and / 10 removes it. In C both keep the sign, so negative numbers work with no special case.

Examples

Example 1 · Input
1234
Expected output
4321
Example 2 · Input
1200
Expected output
21

Hints

Hint 1

n % 10 is the last digit; n / 10 removes it.

Hint 2

Build the answer with rev = rev * 10 + digit.

Hint 3

Handle a negative number by remembering the sign and working with -n.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);
    int sign = n < 0 ? -1 : 1;
    if (n < 0) n = -n;
    int rev = 0;
    while (n > 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    printf("%d\n", sign * rev);
    return 0;
}

Lesson: Loops: for, while and do-while →