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.
class Solution { public: bool isNumber(string s) { int len = s.length(); if(len == 0) return false; int start = 0; while(s[start] == 32) //space { start++; //neglect space at the beginning } if(start >= len) return false; //false if only congtaining space int end = len-1; while(s[end] == 32) { end--;//neglect space at the end } bool hasDot = false; bool hasE = false; bool hasDigit1 = false; //if digit appear before e bool hasDigit2 = false; //if digit appear after e for(int i = start; i<=end; i++) { if(s[i] ==43 || s[i] == 45) //+, - { if(i!=start && s[i-1]!= 101) return false;//false if +,- doesn‘t appear in the beginning, or behind e } else if(s[i] == 46) //. { if(hasDot) return false; //false if two . appear if(hasE) return false; //. cannot appear behind e hasDot = true; } else if(s[i]== 101) //e { if(hasE) return false; //false if appears two e if(!hasDigit1) return false; //false if there‘s no digit before e hasE = true; } else if(s[i]< 48 || s[i] > 57) return false; else if(!hasDigit1) hasDigit1 = true; else if(hasE) hasDigit2 = true; } if((hasE && hasDigit1 && hasDigit2) || (!hasE && hasDigit1)) return true; //at lease one digit must exist; if e appear, at least one digit must appear both before and after e else return false; } };
原文:http://www.cnblogs.com/qionglouyuyu/p/4928632.html