qingcheng奕  

https://oj.leetcode.com/problems/valid-number/

判断给的串,是不是合理的 数字形式

主要问题在需求定义上吧

class Solution {
public:
    bool isNumber(const char *s) {
        if(s == NULL)
            return false;
        
        int index = 0;
        // remove heading spaces
        while(s[index] != '\0' && s[index] == ' ')
            index++;
        
        // only has spaces
        if(s[index] == '\0')
            return false;
        
        // check + or - allowed
        if(s[index] == '+' || s[index] == '-')
            index++;
            
        // remove tailing spaces
        bool hasSpace = false;
        int tailIndex = 0;
        for(int i = index; s[i] != '\0'; i++)
        {
            if(s[i] == ' ')
            {
                if(hasSpace == false)
                    tailIndex = i - 1;
                hasSpace = true;
                continue;
            }
            else if(hasSpace && s[i] != ' ')
                return false;
        
            if(hasSpace == false)
                tailIndex = i;
        }
        
        
        // check only one . and e or digits allowed 
     // . e can't both exists. and 8. is valid
     // before e and after e must has digits
     // + - before them must be e
bool hasNum = false; bool hasDot = false; bool hasE = false; for(int i = index; i != tailIndex + 1 && s[i] != '\0'; i++) { if(s[i] >= '0' && s[i] <= '9') hasNum = true; else if(s[i] == '.') { if(hasDot || hasE) return false; hasDot = true; } else if(s[i] == 'e') { if(hasE || hasNum == false) return false; hasE = true; hasNum = false; } else if(s[i] == '+' || s[i] == '-') { if(!(i > 1 && s[i-1] == 'e')) return false; hasNum = false; } else return false; } return hasNum; } };

 

posted on 2014-08-17 20:29  qingcheng奕  阅读(137)  评论(0编辑  收藏  举报