首页 > 其他 > 详细

65. Valid Number

时间:2015-11-01 21:14:35      阅读:285      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

65. Valid Number

原文:http://www.cnblogs.com/qionglouyuyu/p/4928632.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!