您的位置:首页 > 其它

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;  // 必须有数字
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: