首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Leetcode 题目解析之 Valid Number

Leetcode 题目解析之 Valid Number

原创
作者头像
ruochen
发布2022-02-13 15:17:19
发布2022-02-13 15:17:19
1.4K0
举报

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.

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.

代码语言:javascript
复制
    public boolean isNumber(String s) {
        if (s == null || s.length() == 0) {
            return false;
        }
        char[] chars = s.toCharArray();
        int start = 0, end = chars.length - 1;
        // 除去前后的空格
        while ((start < end) && chars[start] == ' ') {
            start++;
        }
        while ((start < end) && chars[end] == ' ') {
            end--;
        }
        // 因为while的循环条件是start < end,s为空格时,会剩下一个空格
        if (chars[start] == ' ') {
            return false;
        }
        boolean dot = false;
        boolean num = false;
        boolean ex = false;
        for (int i = start; i <= end; i++) {
            char c = chars[i];
            if (c >= '0' && c <= '9') {
                num = true;
            } else if (c == 'e') {
                if (ex)
                    return false;
                if (!num)
                    return false;
                ex = true;
                num = false;
                dot = false;
            } else if (c == '.') {
                if (dot) {
                    return false;
                }
                if (ex) {
                    return false;
                }
                dot = true;
            } else if (c == '+' || c == '-') {
                if (num || dot) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return num;
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档