HDU 2057 A + B Again(16进制加法)
876
2022-08-22
[leetcode] 65. Valid Number
Description
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-9Exponent - “e”Positive/negative sign - “+”/"-"Decimal point - “.”Of course, the context of these characters also matters in the input.
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.
分析
题目的意思是:给定一个字符串,然后判断字符串是否是合法的数字。
leetcode上的hard类型的题目。这道题看似简单,但是没有找到方法却很难做,我参考了leetcode的解法,用.和e E等把字符串分为两部分,然后分开来判断其子字符串是否是数字,如果都是数字并且已经遍历到末尾了,就可以认为这个字符串是合法的。
代码
class Solution {public: bool isNumber(string s) { if(s.empty()){ return false; } int i=0; while(s[i]==' '){ i++; } bool numeric=scanInteger(s,i); if(s[i]=='.'){ i++; numeric=numeric|scanUnsignedInteger(s,i); } if(s[i]=='e'||s[i]=='E'){ i++; numeric=numeric&scanInteger(s,i); } while(s[i]==' '){ i++; } return numeric&&s[i]=='\0'; } bool scanInteger(string s,int& i){ if(s[i]=='+'||s[i]=='-'){ i++; } return scanUnsignedInteger(s,i); } bool scanUnsignedInteger(string s,int& i){ int t=i; while(s[t]>='0'&&s[t]<='9'){ t++; } bool flag=t>i; i=t; return flag; }};
参考文献
[编程题]valid-number
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~