leetcode 65. Valid Number

来源:互联网 发布:淘宝的旺旺名怎么修改 编辑:程序博客网 时间:2024/05/29 13:27

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;    }};