博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指offer——面试题20:表示数值的字符串
阅读量:7004 次
发布时间:2019-06-27

本文共 2167 字,大约阅读时间需要 7 分钟。

1 #include"iostream" 2 using namespace std; 3  4 bool IsInt(const char **str); 5 bool IsUnsignInt(const char **str); 6  7 bool IsNumeric(const char* str) 8 { 9     if(str==nullptr)10         return false;11     bool flagNumeric=IsInt(&str);//二阶指针才能保留更改12 13     if(*str=='.')14     {15         str++;16         flagNumeric=IsUnsignInt(&str)||flagNumeric;//要把flagNumeric放后面17     }18     if(*str=='E'||*str=='e')19     {20         str++;21         flagNumeric=flagNumeric&&IsInt(&str);22     }23     return flagNumeric&&*str=='\0';24 }25 26 bool IsInt(const char **str)//确保*str的内容不被修改27 {28     if(**str=='+'||**str=='-')29         (*str)++;30     return IsUnsignInt(str);31 }32 33 bool IsUnsignInt(const char **str)34 {35     int numLength=0;36     while(**str!='\0'&&**str>='0'&&**str<='9')37     {38      //   cout<<**str;39         (*str)++;40         numLength++;41     }42  //   cout<<**str;43     return numLength>0?true:false;44 }45 46 // ====================测试代码====================47 void Test(const char* testName, const char* str, bool expected)48 {49     if(testName != nullptr)50         printf("%s begins: ", testName);51 52     if(IsNumeric(str) == expected)53         printf("Passed.\n");54     else55         printf("FAILED.\n");56 }57 58 59 int main()60 {61     Test("Test1", "100", true);62     Test("Test2", "123.45e+6", true);63 64     Test("Test3", "+500", true);65     Test("Test4", "5e2", true);66     Test("Test5", "3.1416", true);67     Test("Test6", "600.", true);68     Test("Test7", "-.123", true);69     Test("Test8", "-1E-16", true);70     Test("Test9", "1.79769313486232E+308", true);71 72     printf("\n\n");73 74     Test("Test10", "12e", false);75     Test("Test11", "1a3.14", false);76     Test("Test12", "1+23", false);77     Test("Test13", "1.2.3", false);78     Test("Test14", "+-5", false);79     Test("Test15", "12e+5.4", false);80     Test("Test16", ".", false);81     Test("Test17", ".e1", false);82     Test("Test18", "e1", false);83     Test("Test19", "+.", false);84     Test("Test20", "", false);85     Test("Test21", nullptr, false);86 87     return 0;88 }
View Code

 

转载于:https://www.cnblogs.com/acm-jing/p/10416692.html

你可能感兴趣的文章