String representing the value

Keywords: PHP

Title Description:

   implement a function to determine whether a string represents a numeric value, including integers and decimals. For example, the strings "+ 100","5e2","-123","3.1416" and "- 1E-16" all represent numeric values. But "12e","1a3.14","1.2.3","+-5" and "12e+4.3" are not.

Thought analysis:

   watch the format of the numeric string carefully

   1. If e appears, it is necessary to determine whether there is a number after e, and e cannot appear after E.

   2. If +, - appears for the first time and +, - is not in the first place, then +, - must be after e.

   if the second occurrence of +, -, then +, - must be after e

                    .

Code:

public class Solution {
    public boolean isNumeric(char[] str) {
        if(str==null&&str.length==0)
            return false;
        boolean hasE=false;
        boolean hasDecimal=false;
        boolean hasSign=false;
        for(int i=0;i<str.length;i++){
            if(str[i]=='e'||str[i]=='E'){
                if(i==str.length-1) //e there must be a number at the back
                    return false;
                if(hasE)          //Only one e
                    return false;
                hasE=true;
            }else if(str[i]=='+'||str[i]=='-'){
                if(hasSign&&str[i-1]!='e'&&str[i-1]!='E')//If +, - appears for the second time, it must be after e.
                    return false;
                if(!hasSign&&i>0&&str[i-1]!='e'&&str[i-1]!='E')//If +, - appears for the first time and is no longer the first, it must be after e.
                    return false;
                   hasSign=true;
            }else if(str[i]=='.'){
                if(hasE)           //The decimal point cannot be followed by e
                    return false;
                if(hasDecimal)     //Cannot have two decimal points
                    return false;
                hasDecimal=true;
            }else if(str[i]<'0'||str[i]>'9'){
                return false;
            }
        }
        return true;
    }
}

Posted by ericburnard on Sat, 02 Nov 2019 16:02:28 -0700