Thursday, May 28, 2015

L Question: is Number

public static boolean isNumber(String str) {
  int n = str.length();
  boolean hexFound = false;
  boolean decimalFound = false;
  boolean numFound = false;
  boolean signFound = false;
  boolean zeroFound = false;
  for(int i = 0; i < n ; i++) {
   char ch = str.charAt(i);
   switch(ch) {
    case '-':
    case '+':
     if(signFound || i != 0) {
      return false;
     } else {
      signFound = true;
     }
    break;
    
    case '.':
     if(hexFound || decimalFound || i == n-1) {
      return false;
     } else {
      decimalFound = true;
     }
    break;
    
    case 'x': 
     if(!zeroFound || hexFound || numFound || signFound) {
      return false;
     } else {
      hexFound = true;
     }
    break;
    
    case '0':
     zeroFound = true;
    break;
    
    default:
     if(ch >= 'a' && ch <='f') {
      if(!hexFound) {
       return false;
      }
     } else if(ch >= '0' && ch <= '9') {
      numFound = true;
     } else {
      return false;
     }
   }
  }
  return true;
 }

No comments:

Post a Comment