leetcode 65. 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.

这道题就是判断一个字符串是否是数组,我是直接借助库函数实现的,网上还与其他的解法,我这里是偷懒了,我个人不喜欢这样的题。

代码如下:

public class Solution 
{
    public boolean isNumber(String s) 
    {
        if(s.endsWith("f") || s.endsWith("F") || s.contains("D"))
            return false;

        boolean res=true;
        try 
        {
            Double.parseDouble(s);      
        } catch (NumberFormatException e) 
        {
            res=false;
        }

        return res;
    }       
}

下面是C++的做法,但是没法做到AC,但是我还是倾向这么做

代码如下:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

class Solution 
{
public:
    bool isNumber(string s) 
    {
        stringstream ss;
        ss << s;
        long double d;
        char c;

        /*
        ss>>d表示把sin转换成double的变量(其实对于int和float型的都会接收),如果转换成功,则值为非0,如果转换不成功就返回为0
        */
        if ( ! (ss >> d) )
            return false;

        /*
        此部分用于检测错误输入中,数字加字符串的输入形式(例如:34.f),在上面的的部分(ss>>d)已经接收并转换了输入的数字部分,
        在stringstream中相应也会把那一部分给清除,如果此时传入字符串是数字加字符串的输入形式,则此部分可以识别并接收字符部分,
        例如上面所说的,接收的是.f这部分,所以条件成立,返回false;如果剩下的部分不是字符,那么则sin>>p就为0,则进行到下一步else里面
        */
        if (ss >> c)
            return false;
        else
            return true;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值