Problem
Validate if a given string can be interpreted as a decimal number.
Some examples:
"0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true " -90e3 " => true " 1e" => false "e3" => false " 6e-1" => true " 99e2.5 " => false "53.5e93" => true " --6 " => false "-+3" => false "95a54e53" => false
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
Numbers 0-9 Exponent - "e" Positive/negative sign - "+"/"-" Decimal point - "."
Of course, the context of these characters also matters in the input.
Solutionclass Solution { public boolean isNumber(String s) { if (s == null || s.length() == 0) return false; s = s.trim(); int len = s.length(); if (len == 0) return false; int signCount = 0; boolean hasE = false; boolean hasNum = false; boolean hasPoint = false; for (int i = 0; i < len; i++) { char ch = s.charAt(i); if (ch >= "0" && ch <= "9") { hasNum = true; } else if (ch == "e" || ch == "E") { if (hasE || !hasNum || i == len-1) return false; hasE = true; } else if (ch == ".") { if (hasPoint || hasE) return false; //0. is true if (i == len-1 && !hasNum) return false; hasPoint = true; } else if (ch == "+" || ch == "-") { //two signs at most; should not appear in the end if (signCount == 2 || i == len-1) return false; //sign appears in the middle but no E/e if (i > 0 && !hasE) return false; signCount++; } else return false; } return true; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72364.html
摘要:完整的正则表达式为。代码如下翻译如果我们看到数字,就将设为如果看到小数点,则判断是否已有小数点或是,因为后只能有整数只能遇到一次,如果第一次遇到但是没有遇到数字,则返回错误。 题目要求 Validate if a given string is numeric. Some examples: 0 => true 0.1 => true abc => false 1 a => fa...
摘要:描述分析该题的说明比较模糊,所以需要慢慢进行尝试来弄清楚哪些是合法的数字。代码去除前后的空格小数点前面不能出现和小数点前面不能出现,并且需要有数字保证后面也有数字符号只能再位和后面一位 描述 Validate if a given string is numeric. Some examples:0 => true 0.1 => trueabc => false1 a => fals...
摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
Problem Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.Examp...
摘要:描述累加数是一个字符串,组成它的数字可以形成累加序列。一个有效的累加序列必须至少包含个数。说明累加序列里的数不会以开头,所以不会出现或者的情况。示例输入输出解释累加序列为。 LeetCode 306. Additive Number Description Additive number is a string whose digits can form additive sequen...
阅读 2923·2023-04-26 01:52
阅读 3450·2021-09-04 16:40
阅读 3616·2021-08-31 09:41
阅读 1707·2021-08-09 13:41
阅读 471·2019-08-30 15:54
阅读 2910·2019-08-30 11:22
阅读 1585·2019-08-30 10:52
阅读 932·2019-08-29 13:24