From 2e0af9787c1998c1faad84fdab33c92170c6972f Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 6 Aug 2017 07:29:27 +0800 Subject: [PATCH] Valid number Signed-off-by: Leo Ma --- 065_valid_number/Makefile | 2 + 065_valid_number/valid_number.c | 65 +++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 065_valid_number/Makefile create mode 100644 065_valid_number/valid_number.c diff --git a/065_valid_number/Makefile b/065_valid_number/Makefile new file mode 100644 index 0000000..bef5548 --- /dev/null +++ b/065_valid_number/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test valid_number.c diff --git a/065_valid_number/valid_number.c b/065_valid_number/valid_number.c new file mode 100644 index 0000000..36a0c5e --- /dev/null +++ b/065_valid_number/valid_number.c @@ -0,0 +1,65 @@ +#include +#include +#include + +static bool isNumber(const char *s) { + bool point = false; + bool hasE = false; + + //trim the space + while(isspace(*s)) s++; + //check empty + if (*s == '\0' ) return false; + //check sign + if (*s=='+' || *s=='-') s++; + + const char *head = s; + for(; *s!='\0'; s++){ + // if meet point + if ( *s == '.' ){ + if ( hasE == true || point == true){ + return false; + } + if ( s == head && !isdigit(*(s+1)) ){ + return false; + } + point = true; + continue; + } + //if meet "e" + if ( *s == 'e' ){ + if ( hasE == true || s == head) { + return false; + } + s++; + if ( *s=='+' || *s=='-' ) s++; + if ( !isdigit(*s) ) return false; + + hasE = true; + continue; + } + //if meet space, check the rest chars are space or not + if (isspace(*s)){ + for (; *s != '\0'; s++){ + if (!isspace(*s)) return false; + } + return true; + } + if ( !isdigit(*s) ) { + return false; + } + + } + + return true; +} + +int main(int argc, char** argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test number\n"); + exit(-1); + } + printf("%s\n", isNumber(argv[1]) ? "true" : "false"); + return 0; +}