Java - is string a valid number


  • 0
    V

    Here's a solution to find, if a give string is a valid number with range of inputs.

    Time : O(n)

    public class ValidNumber {
        
        public static void main(String[] args) {
            // Inputs
            String s = "-1.234";     //Valid
            // String s = "1234.0";     //Valid
            // String s = ".123";       //Invalid
            // String s = "123.";       //Invalid
            // String s = "2.2.2";      //Invalid
            // String s = "-1234-1";    //Invalid
    
            System.out.println(s+" is : "+(isValidNumber(s) ? "Valid Number" : "Invalid number"));
        }
        
        private static boolean isValidNumber(String str) {
            char[] charArray = str.toCharArray();
            int n = charArray.length;
            int dotCounter = 0;
    
            if (charArray[0] == '.' || charArray[n-1] == '.') {
                return false;
            }
    
            for(int i = 0; i < n; i++) {
    
                if (charArray[i] == '-' && i > 0) {
                    return false;
                }
    
                if (charArray[i] == '.') {
                    dotCounter++;
                }
    
                if (dotCounter > 1) {
                    return false;
                }
    
                if (charArray[i] != '-' &&  charArray[i] != '.' && !Character.isDigit(charArray[i])) {
                    return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.