[LeetCode-Algorithms-65] "Valid Number" (2017.11.1-WEEK9)

题目链接:Valid Number


  • 题目描述:

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.


(1)思路:判断一个字符串是不是数字。
a.排除首尾空格
b.排除头部符号位
c.剩下的字符串再进行检查。
    在碰到e之前,判断字符是否是 0-9 的数字或小数点。要注意.1 和1. 这种格式都是可以被判断为数字的。
    碰到指数之后,后面不能有小数点,指数后面第一位可以是符号位,其余只能是数字。
(2)代码:
class Solution {
public:
    bool isNumber(string s) {
      auto realStart = s.find_first_not_of(' ');
      auto realEnd = s.find_last_not_of(' ');
      int num_count = 0, exp_count = 0, point_count = 0;
      bool exp_flag = false;
      if (s[realStart] == '+' || s[realStart] == '-') realStart++;
      for (auto i = realStart; i <= realEnd; i++) {
        if (exp_flag) {
          if (exp_count == 0 && num_count == 0 && (s[i] == '+' || s[i] == '-')) exp_count = 1;
          else if (s[i] <= '9' && s[i] >= '0') num_count++;
          else return false;
        } 
        else {
          if (s[i] == 'e') {
            if (num_count == 0) return false;
            exp_flag = true;
            num_count = 0;
          }
          else if (s[i] <= '9' && s[i] >= '0') num_count++;
          else if (s[i] == '.') point_count++; 
          else return false;    
        }
      }
      if (num_count < 1 || point_count > 1) return false;
      return true;
    }
};
(3)提交结果:

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值