Safe String to Integer Conversion

easy Programming Basics

Problem

Read one word. If it is a whole number (an optional + or - sign followed by digits only) and it fits in a signed 32-bit integer, print the number. Otherwise print Invalid. Example: 007 gives 7. Example: 12a gives Invalid.

Constraints

  • The word has 1 to 30 characters, no spaces

Examples

Input

12a

Output

Invalid

Input

007

Output

7

Solutions

Best approachTime O(n)Space O(1)

Never trust input. Java reports a bad number with an exception, so we catch it. In JavaScript and Python we check the text and the range ourselves.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Convert text to a 32-bit integer safely.
 * Input   : One word without spaces.
 * Output  : The integer, or Invalid.
 * Approach: Check the text before you convert.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

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

        // Step 1: Try to convert. parseInt throws an exception for bad text or for a value outside the int range.
        try {
            int value = Integer.parseInt(text);

            // Step 2: The text was good. Print the number.
            System.out.println(value);
        } catch (NumberFormatException error) {
            // Step 3: The text was bad. Print Invalid.
            System.out.println("Invalid");
        }
    }
}
Hints (2)
  1. What happens in Java when the text is 12a?
  2. Which range does a 32-bit int have?