LeetCode Online Judge 题目C# 练习 - Valid Number

Validate if a given string is numeric
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

 1         public static bool ValidNumber(string s)

 2         {

 3             s = s.Trim();

 4             int eindex = s.IndexOf('e');

 5 

 6             if (eindex == -1)

 7                 return isValidNumber(s);

 8 

 9             string s1 = s.Substring(0, eindex);

10             string s2 = s.Substring(eindex + 1);

11             return isValidNumber(s1) && isValidNumber(s2);

12         }

13 

14         public static bool isValidNumber(string s)

15         {

16             int dot = 0;

17             for (int i = 0; i < s.Length; i++)

18             {

19                 // not valid char?

20                 if (s[i] != '+' && s[i] != '-' && s[i] != '.' && !(s[i] >= '0' && s[i] <= '9'))

21                     return false;

22 

23                 // '+' or '-' in the middle?

24                 if (i > 0 && (s[i] == '+' || s[i] == '-'))

25                     return false;

26 

27                 // more than two '.'?

28                 if (s[i] == '.' && dot > 0)

29                     return false;

30                 // count dot

31                 else if(s[i] == '.')

32                     dot++;

33             }

34 

35             return true;

36         }

代码分析:

  正如题目所说的,这里充满了讨论的空间,什么是valid number 什么不是,面试官说了算。

你可能感兴趣的:(LeetCode)