Valid Number
2015-07-13 00:16
375 查看
Question
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.
My Solution
class Solution { public: bool isNumber(string s) { int size = s.size(); // 预处理,去除左右两边空格 int countLS = 0; // 左边空格 int countRS = 0; // 右边空格 int idx = 0; // 指向下一个字符位置 char c; while(isSpace(s[idx++])) // count spaces in left { countLS++; } idx = size - 1; while(isSpace(s[idx--])) // count spaces in right { countRS++; } size -= countLS + countRS; for(idx = 0; idx < size; idx++) { s[idx] = s[idx + countLS]; } s[size] = '\0'; int ePos = s.find('e'); // e出现的位置 string lStr; string rStr; if(ePos != string::npos) // 找到了'e' { lStr = s.substr(0, ePos); rStr = s.substr(ePos + 1, size - ePos - 1); if(isPotDig(lStr) && isInteger(rStr)) { return true; } }else // 都没有找到 { return isPotDig(s); } return false; } bool isSpace(char c) { if(' ' == c || '\t' == c || '\n' == c) return true; else return false; } /*********** * 判断小数 * *********/ bool isPotDig(string s) { int size = -1; while('\0' != s[++size]) { } int pPos = s.find('.'); // .出现的位置 if(pPos != string::npos) // 找到了'.' { string lStr = s.substr(0, pPos); string rStr = s.substr(pPos + 1, size - pPos - 1); if(pPos == 0 && isDigNum(rStr, false, false)) // 左边为空右边为数字 { return true; } if(isDigNum(lStr, true, false) && pPos + 1 >= size) // 左边数字右边空 { return true; } if(isDigNum(lStr, true, true) && isDigNum(rStr, false, false)) // 两边都为数字 { return true; } return false; }else { return isInteger(s); } } /*********** * 判断整数 * *******/ bool isInteger(string s) { return isDigNum(s, true, false); } /****************** * 判断是否有且仅有数字,可以包括符号(不包含'.'和'e' * ****************/ bool isDigNum(string s, bool sign = false /*是否允许一个符号位*/, bool noDigAfterSign = false/*符号位后面是否允许空*/) { int idx = 0; char c; bool noDig = true; bool noSign = true; if(sign) // 对符号位做预处理,符号位后面必须接数字 { if(s[0] == '-' || s[0] == '+') { idx++; noSign = false; } } while('\0' != (c = s[idx++])) { if(c >= '0' && c <= '9') { noDig = false; // have digit continue; } return false; // 有异常字符 } // 运行到此处,说明没有异常字符 if(noDigAfterSign && !noSign) // 有符号位,且允许没有数字,则任何情况都满足 { return true; }else { return !noDig; // 必须有数字 } } };
相关文章推荐
- NameService与NameSpace
- html 框架学习
- PHP output_buffering 你了解多少
- MYSQL学习笔记(四)之常见的字符串函数
- 游戏引擎多线程
- zb的生日(暴搜dfs)
- Skype for Business Server 2015-13-IISARR-2-发布-1-OWA-ECP
- 流媒体传输协议学习汇总
- 文章标题
- [Oracle] - Create DB on Oracle 12c for an Application
- 函数的相关思考
- 转载Android常见问题
- 连续整数固定和(C百例)
- Linux发行版收藏
- Google将Material Design带到CSS、HTML与JavaScript上
- Maximum number of WAL files in the pg_xlog directory (2)
- 广义表的创建和遍历
- mysql数据双向同步实现
- Java线程:概念与原理
- 指针与引用