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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 2941·2023-04-26 01:52
閱讀 3468·2021-09-04 16:40
閱讀 3629·2021-08-31 09:41
閱讀 1764·2021-08-09 13:41
閱讀 556·2019-08-30 15:54
閱讀 2960·2019-08-30 11:22
閱讀 1612·2019-08-30 10:52
閱讀 948·2019-08-29 13:24