LintCode刷题:有效数字

来源:互联网 发布:word of mac 迅雷下载 编辑:程序博客网 时间:2024/04/30 18:52

       今天第一次是跟随一个博主学习足迹知道有LintCode 和LeetCode这两个刷题网址,专为学编程的同志练手,我希望我可以每天坚持刷一题!!!!

       第一次不知道直接点“帮我挑一题”,给了我《有效数字》这道题。一看到这道题感觉还蛮简单的,可写才知道自己的基础 是多么的薄弱,内心那个崩溃啊!而且不知道为什么我在线写的Java程序总是有错的,但是我复制到我eclipse中运行时对的,最后无奈找了这道题的c++版的程序。

题目:有效数字

要求:http://www.cnblogs.com/peijie-tech/p/3540170.html。希望可以得到如下效果:

"0" => true

" 0.1 " => true

"abc" => false

"1 a" => false

"2e10" => true

程序 :

public class isNumber {public static void main(String[] args) {        String str="123456";        isNumber a=new isNumber();        boolean result=a.effNumber(str);        System.out.print(str+'是'+result);}public boolean effNumber(String str){        return str.matches("[0-9]+");    }}

c++程序:

class Solution {public:    /**     * @param s the string that represents a number     * @return whether the string is a valid number     */    bool isNumber(string& s) {        // Write your code here        int start = 0;        int end = s.length() - 1;        // trim leading spaces        while (start <= end && s[start] == ' ')            start++;         if(start > end) //empty            return false;         //trim trailing spaces        while(s[end] == ' ')            end--;         // skip leading +/-        if (s[start]== '+' || s[start] == '-')            start++;         bool num = false; // is a digit        bool dot = false; // is a '.'        bool exp = false; // is a 'e'        while(start <= end) {            if (s[start] >= '0' && s[start] <= '9') {                num = true;            } else if (s[start] == '.') {                if (exp || dot)                    return false;                dot = true;            } else if (s[start] == 'e') {                if(exp || num == false)                    return false;                exp = true;                 num = false;            } else if (s[start] == '+' || s[start] == '-') {                if (s[start - 1] != 'e')                    return false;            } else {                return false;            }            start++;        }        return num;    }};
大家还有什么比较好的方法告诉我一下哈!最好是Java版的,参考博文:http://www.cnblogs.com/peijie-tech/p/3540170.html


原创粉丝点击