题解 | #表示数值的字符串#
表示数值的字符串
https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return bool布尔型 */ public boolean isNumeric (String str) { int index = 0; // 首先去除字符串两端空格 str = str.trim(); int length = str.length(); if (length == 0) return false; char[] string = str.toCharArray(); // 读取整数或小数 // 跳过可能的正负号 char ch = string[index]; if (ch=='+' || ch=='-') { index++; } // 读取小数或整数的第一个字符, 他可能是 数字 点,其他的均为错误 if (index >= length) return false; ch = string[index]; boolean hasDot = false; if (Character.isDigit(ch)) { index++; } else if (ch == '.') { index++; hasDot = true; } else { return false; } // 如果是点,点后必须有数字 if (hasDot && index>=length) return false; // 接着往下读,如果没读到点,那么就可能读到一个小数点 // 如果已经读到了,再读到一个小数点那肯定出错了 while (index < length) { ch = string[index]; if (Character.isDigit(ch)) { index++; } else if (!hasDot && ch=='.') { index++; hasDot = true; } else if (hasDot && ch=='.') { return false; } else { break; } } if (index >= length) return true; // 现在看看是不是读到 E e 了 ch = string[index]; if (ch=='E' || ch=='e') { index++; } else { return false; } // 走到这里,我们就读到了一个科学技术法,后面必须得有一个整数 if (index >= length) return false; ch = string[index]; if (ch=='+' || ch=='-') { index++; } // 后面的必须是数字 if (index >= length) return false; while (index < length) { if (Character.isDigit(string[index])) { index++; } else { break; } } return index==length ? true : false; } }