lintcode,有效数字

    xiaoxiao2021-12-14  18

    给定一个字符串,验证其是否为数字。 样例 “0” => true ” 0.1 ” => true “abc” => false “1 a” => false “2e10” => true

    解题思路:先把特殊符号替换掉,然后逐位对比是否合法。代码ac了,但是发现是错误的,我没注意e的问题。有e的话要区别对待,而且我一开始把+-号替换掉也是不对的。

    public class Solution { /** * @param s the string that represents a number * @return whether the string is a valid number */ public boolean isNumber(String s) { s = s.trim(); s = s.replace(".",""); s = s.replace("+",""); s = s.replace("-",""); if(s == null || s.length() == 0) return false; int len = s.length(); for(int i = 0; i < len; i++){ char ch = s.charAt(i); int tmp = ch - '0'; if(tmp < 0 || tmp > 9){ return false; } } return true; } }

    参考别人的修改了一下,下面的也ac了,应该可以。

    public class Solution { /** * @param s the string that represents a number * @return whether the string is a valid number */ public boolean isNumber(String s) { s = s.trim(); if(s == null || s.length() == 0) return false; int len = s.length(); int i = 0; if(s.charAt(0) == '+' || s.charAt(0) == '-') i++; boolean number = false; boolean exp = false; boolean dot = false; while(i++ < len){ char ch = s.charAt(i-1); int tmp = ch - '0'; if (tmp >= 0 && tmp <= 9) { number = true; } else if(ch == '.'){ if(dot || exp ) return false; dot = true; } else if(ch == 'e'){ if(number == false || exp || dot) return false; number = false; exp = true; }else { return false; } } return number; } }
    转载请注明原文地址: https://ju.6miu.com/read-971306.html

    最新回复(0)