basics · intermediate · ~15 min
Encode acceptance rules as states.
Check that a string is a valid signed integer, encoding the rules as a small state machine.
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.
A NUL-terminated string s.
Returns 1 if s is a well-formed signed integer, otherwise 0.
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
+ or - with no digits is invalid.A NUL-terminated string s.
1 if s is a valid signed integer, otherwise 0.
Optional +/- sign then 1+ digits; empty and sign-only are invalid.
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.