lintcode,有效数字
来源:互联网 发布:套马杆网络歌手演唱 编辑:程序博客网 时间:2024/05/01 00:06
给定一个字符串,验证其是否为数字。
样例
“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; }}
0 0
- LintCode:有效数字
- lintcode,有效数字
- lintcode 有效数字
- 有效数字-LintCode
- LintCode刷题:有效数字
- [Lintcode]Valid Number有效数字
- LINTCODE——有效数字(待改进)
- lintcode-有效回文字符串
- LintCode : 有效回文串
- LintCode-有效回文串
- lintcode --有效回文串
- 有效回文串,lintcode
- lintcode:有效回文串
- 有效回文串-LintCode
- 有效数字
- 有效数字
- 有效数字
- lintcode 有效的括号序列
- Struts框架搭建
- Eclipse中文乱码解决方法总结
- JAVA带你一步一步实现微信公众号开发(一)
- 【Dongle】【Java】基础(五)之包及引用
- Ubuntu16.04 LTS安装Android studio
- lintcode,有效数字
- Android 动画之interpolator
- 线性表
- Chapter 1 Python交互模式下方向键乱码
- 编程之法(单词翻转)
- stm32固件库assert_param()
- 每日一则(2):call apply bind
- 【PAT】PAT-JAVA-5-2 然后是几点 (15分)
- CSS3新特性