Reverse a Number

easy Number Problems

Problem

Read an integer and print the number with its digits in reverse order. Keep the minus sign. Leading zeros of the result disappear: 1200 becomes 21.

Constraints

  • -10^18 <= n <= 10^18 (the reversed value must fit in 64 bits)

Examples

Input

1234

Output

4321

Input

1200

Output

21

Solutions

Best approachTime O(d)Space O(1)

Each loop takes the last digit of the input and appends it to the result: result = result * 10 + digit. The first digit we take becomes the last digit of the result.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Reverse the digits of an integer.
 * Input   : One integer.
 * Output  : The reversed integer.
 * Approach: Build the result by adding one digit at a time.
 * Time    : O(d)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        long number = new Scanner(System.in).nextLong();

        // Step 1: Remember the sign. We work with a positive number and add the sign at the end.
        boolean isNegative = number < 0;
        number = Math.abs(number);

        // Step 2: The result starts at 0. We use long because a reversed number can be larger than int.
        long reversed = 0;

        // Step 3: Repeat until no digits are left.
        while (number > 0) {
            // Step 4: Take the last digit. Example: 1234 % 10 = 4.
            long digit = number % 10;

            // Step 5: Move the old result one place to the left and add the digit. Example: 4 * 10 + 3 = 43.
            reversed = reversed * 10 + digit;

            // Step 6: Remove the last digit. Example: 1234 / 10 = 123.
            number = number / 10;
        }

        // Step 7: Put the minus sign back if the input was negative.
        System.out.println(isNegative ? -reversed : reversed);
    }
}
Hints (2)
  1. Build the answer one digit at a time.
  2. Multiplying by 10 makes room for a new last digit.