[LeetCode #65] Valid Number

Valid Number
Validate if a given string is numeric.

Some examples:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

public class Solution {
	public boolean isNumber(String s) {
		s = s.trim();
		if ( s.isEmpty()) {
			return false;
		}
		
		String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?";
		if ( s.matches(regex)) {
			return true;
		} else {
			return false;
		}
			
	}

	public static void main(String args[]) {
		Solution s = new Solution();
		if (false != s.isNumber("...")) {
			System.out.println("Something is wrong !!!");
		}
		if (true != s.isNumber("0")) {
			System.out.println("Something is wrong !!!");
		}

		if (true != s.isNumber(" 0.1 ")) {
			System.out.println("Something is wrong !!!");
		}
		if (false != s.isNumber("abc")) {
			System.out.println("Something is wrong !!!");
		}
		if (false != s.isNumber("1 a")) {
			System.out.println("Something is wrong !!!");
		}
		if (true != s.isNumber("2e10")) {
			System.out.println("Something is wrong !!!");
		}
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s