basics · intermediate · ~15 min

Validate a number string

Encode acceptance rules as states.

Challenge

Check that a string is a valid signed integer, encoding the rules as a small state machine.

Task

Implement int valid_number(const char *s) that returns 1 if s is a valid signed integer and 0 otherwise. Valid means: an optional leading + or -, followed by one or more decimal digits, and nothing else. The empty string and a lone sign are invalid. No main — the grader calls it.

Input

A NUL-terminated string s.

Output

Returns 1 if s is a well-formed signed integer, otherwise 0.

Example

valid_number("123")   ->   1
valid_number("-45")   ->   1
valid_number("+0")    ->   1
valid_number("12a")   ->   0     (trailing non-digit)
valid_number("-")     ->   0     (sign with no digits)
valid_number("")      ->   0

Edge cases

  • A lone + or - with no digits is invalid.
  • The empty string is invalid.
  • Any non-digit after the optional sign makes it invalid.

Rules

  • Accept exactly: optional sign, then one-or-more digits, then end-of-string.

Input format

A NUL-terminated string s.

Output format

1 if s is a valid signed integer, otherwise 0.

Constraints

Optional +/- sign then 1+ digits; empty and sign-only are invalid.

Starter code

int valid_number(const char *s) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.