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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
正如題意,這個題題意太模糊的了,在沒有面試官和提示的情況下,只能一次次試,看哪些情況是不合法的,然後更正程序
1.空格只有在左右兩邊是合法的,在其他位置都非法
2.點的左右必須至少有一個數字
3.e|E之前必須有合法的numeric,包括小數和整數。
4.e|E之後必須是合法的整數,包括正數和負數
class Solution { public: int getNonNumericIndex(string& str,int strSize,int startPos) { int i=startPos; for(;i<strSize && (str[i]>='0' && str[i]<='9');i++); return i>strSize ? strSize:i; } bool isValidInt(string& str,int strSize,int startPos) { if(startPos>=strSize){ return false; } int i = startPos; if(str[i]=='+' || str[i]=='-'){ i++; } if(i==strSize){ return false; } i =getNonNumericIndex(str,strSize,i); return i==strSize? true:false; } bool isValidDot(string& str,int strSize,int startPos,int dotPos) { if(dotPos == startPos){ if(dotPos+1==strSize){ return false; } if(str[dotPos+1]<'0'|| str[dotPos+1]>'9'){ return false; } } if(dotPos+1==strSize){ if(str[dotPos-1]<'0'|| str[dotPos-1]>'9'){ return false; } } if((str[dotPos-1]<'0'|| str[dotPos-1]>'9') && (str[dotPos+1]<'0'|| str[dotPos+1]>'9')) { return false; } return true; } bool isNumber(string& str,int strSize) { if(strSize==0){ return false; } int start=0; if(str[0]=='+' || str[0]=='-'){ start++; } if(start==strSize){ return false; } int nonNumericIndex = getNonNumericIndex(str,strSize,start); if(nonNumericIndex<strSize){ if(str[nonNumericIndex] == '.'){ if(!isValidDot(str,strSize,start,nonNumericIndex)){ return false; } nonNumericIndex = getNonNumericIndex(str,strSize,nonNumericIndex+1); if(nonNumericIndex<strSize){ if(str[nonNumericIndex] == 'e' || str[nonNumericIndex] == 'E'){ return isValidInt(str,strSize,nonNumericIndex+1); }else{ return false; } } }else if(str[nonNumericIndex] == 'e' || str[nonNumericIndex] == 'E'){ if(nonNumericIndex==start){ return false; } if(str[nonNumericIndex-1]<'0' || str[nonNumericIndex-1]>'9'){ return false; } return isValidInt(str,strSize,nonNumericIndex+1); }else{ return false; } } return true; } bool isNumber(string &str) { string tmpStr; int start = 0,end=str.size(); for(;start<end && str[start]==' ';start++); for(;end>=1 && str[end-1]==' ';end--); for(;start<end;start++){ tmpStr.push_back(str[start]); } return isNumber(tmpStr,tmpStr.size()); } };