[leetcode-65]Valid Number(C语言)
2015-07-13 21:52
656 查看
问题描述:
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.
代码分析:这道题巨**恶心,关键是有些规则并不清楚,需要一次一次的得到测试用例之后才知道规则。另外,这道题建议分开写,而不是混杂在一起,实在是太乱了。总的来说,如果存在e,那么e之前一定为一个float,后面为一个整数。如果不存在e,就检查整体是否为float。
代码如下:8ms
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.
代码分析:这道题巨**恶心,关键是有些规则并不清楚,需要一次一次的得到测试用例之后才知道规则。另外,这道题建议分开写,而不是混杂在一起,实在是太乱了。总的来说,如果存在e,那么e之前一定为一个float,后面为一个整数。如果不存在e,就检查整体是否为float。
代码如下:8ms
[code]bool checkFloat(char *s,int start,int end){ if(start>end) return false; int i; int pointNums = 0; for(i = start;i<=end;i++){ if(s[i]=='.'){ pointNums++; if(start==end||pointNums>1) return false; } else if(s[i]<'0'||s[i]>'9') return false; } return true; } //闭区间 bool checkInt(char *s,int start,int end){ if(start<=end&&(s[start]=='+'||s[start]=='-')) start++; if(start>end) return false; int i; for(i = start;i<=end;i++){ if(s[i]<'0'||s[i]>'9') return false; } return true; } bool isNumber(char* s) { int i; int startIndex,endIndex; int length = strlen(s); //delete the space from head; for(startIndex = 0;startIndex<length;startIndex++) if(s[startIndex]!=' ') break; //delete the space from tail for(endIndex = length-1;endIndex>=0;endIndex--) if(s[endIndex]!=' ') break; //delete the +/1 from head while(startIndex<=endIndex&&(s[startIndex]=='+'||s[startIndex]=='-')) startIndex++; if(startIndex>endIndex) return false; for(i = startIndex;i<=endIndex;i++){ if(s[i] == 'e'||s[i] == 'E'){ bool tmp1 = checkFloat(s,startIndex,i-1); bool tmp2 = checkInt(s,i+1,endIndex); if(tmp1&&tmp2) return true; else return false; } } //没有e return checkFloat(s,startIndex,endIndex); }
相关文章推荐
- 来北京的日子(2)
- 【学习笔记】【OC语言】类方法
- C++多线程学习
- POJ 3468
- 循环首次适应算法、首次适应算法、最佳适应算法_C语言版
- c/c++ # 与 ##
- C语言入门学习总结(一)
- C语言时间处理
- C语言中函数的妙用
- c++builder自定义控件
- C++常用术语及其英文翻译的含义和简单用途总结(一)
- C++ 学习之函数重载、基于const的重载
- [C++] const与重载
- C++中const重载
- vs2010下C++调用lib或dll文件
- C语言基础之--------内存地址分配
- C语言基础———指针,结构体指针,函数指针
- ZOJ2714迭代更新
- C语言基础---------函数,结构体
- C语言基础-----二维数组,三维数组