zoukankan      html  css  js  c++  java
  • 剑指Offer:表示数值的字符串

    剑指Offer:表示数值的字符串

    题目描述:
    请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、“0123"及”-1E-16"都表示数值,但"12e"、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。

    解题思路:

    1. 将字符串中的首尾空格去除;
    2. e/E为分隔符,将字符串分为底数和指数字符串;
    3. 底数+/-只能有一个且必须是第一个位置,. (点) 只能有一个,数字必须在0~9范围;
    4. 指数中+/-只能有一个且必须是第一个位置,不能有.(点),数字必须在0~9范围。
    class Solution {
    public:
        bool isNumber(string s) 
        {
            //string::size_type pos;
            int pos;
            int begin = 0, end = s.size()-1;
            /* 找出所有空格*/
            while (begin < end && s[end] == ' ') end--; 
            while (begin < end && s[begin] == ' ') begin++;
            s=s.substr(begin, end-begin+1);
            if (s.empty())
                return false;
    
            int e=s.find('e');
            int E=s.find('E');
            if ( e==string::npos )
            {
                return deal_bottom(s); 
            }
            else 
            {   
                if (e >= 0)
                    pos=e;
                else if(E >= 0)
                    pos=E;
                return deal_bottom(s.substr(0, pos)) && deal_index(s.substr(pos+1));
            }
        }
    
            bool deal_bottom(string a)
            {
                bool point=false;
                bool result=false;
                for (int i=0; i < a.size(); i++)
                {
                    if (a[i]=='+' || a[i]=='-')
                    {
                        if (i != 0) 
                            return false;
                    }
                    else if (a[i]=='.')
                    {
                        if (point)
                            return false;
                        point=true;
                    }
                    else if (a[i] < '0' || a[i] > '9')
                    {
                        return false;
                    }
                    else
                        result=true;
                }
                return result;
            }
    
            bool deal_index(string b)
            {
                bool result=false;
                for (int i=0; i < b.size(); i++)
                {
                    if (b[i]=='+' || b[i]=='-')
                    {
                        if (i != 0) 
                            return false;
                    }
                    else if (b[i] < '0' || b[i] > '9')
                    {
                        return false;
                    }
                    else
                        result=true;
                }
                return result;
            }
    };
    
  • 相关阅读:
    用户描述
    课堂练习
    一阶段11.21
    一阶段11.20
    一阶段 11.19
    自己动手写spring(五) bean的生命周期管理
    自己动手写spring(四) 整合xml与注解方式
    自己动手写spring(三) 支持注解方式
    自己动手写spring(二) 创建一个bean工厂
    自己动手写spring(一) 使用digester
  • 原文地址:https://www.cnblogs.com/Tavi/p/12514021.html
Copyright © 2011-2022 走看看