剑指offer-题54:表示数值的字符串

该博客探讨了如何实现一个函数,用于判断输入的字符串是否表示数值,包括整数和小数。提到了一些合法和不合法的字符串示例,并提到了在牛客网上的实验平台。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。

实验平台:牛客网


解决思路:

这里写图片描述

java:

public class Solution {
    public boolean isNumeric(char[] str) {
        int strLenght = str.length;
        if (str == null || strLenght == 0) {
            return false;
        }
        int index = 0;
        if (str[index] == '+' || str[index] == '-') {
            index++;
        }
        if (index == strLenght) {
            return false;
        }
        // 整数0~9部分
        while (index < strLenght && str[index] >= '0' && str[index] <= '9') {
            index++;
        }
        if (index != strLenght) {
            if (str[index] == '.') {// 含有小数点时
                index++;
                while (index < strLenght && str[index] >= '0' && str[index] <= '9') {
                    index++;
                }
                if (index < strLenght && (str[index] == 'e' || str[index] == 'E')) {
                    return isExponential(str, strLenght, index);
                }
            } else if (str[index] == 'e' || str[index] == 'E') {
                return isExponential(str, strLenght, index);
            } else {
                return false;
            }
        }
        return index == strLenght;
    }

    // 判断是否是科学计数法
    public boolean isExponential(char[] str, int strLenght, int index) {
        index++;
        if (index < strLenght && (str[index] == '+' || str[index] == '-')) {
            index++;
        }
        if (index == strLenght) {
            return false;
        }
        while (index < strLenght && str[index] >= '0' && str[index] <= '9') {
            index++;
        }
        return index == strLenght ? true : false;
    }
}

python:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值