Skip to content

Instantly share code, notes, and snippets.

@M-ZubairAhmed
Created March 17, 2017 05:19
Show Gist options
  • Save M-ZubairAhmed/18af9e967df31b2567cafa3eb033dd7b to your computer and use it in GitHub Desktop.
Save M-ZubairAhmed/18af9e967df31b2567cafa3eb033dd7b to your computer and use it in GitHub Desktop.
Algorithm to check if agiven is a valid hexadecimal number.
public class StringUtils {
public static boolean isHexNumber(String s) {
int cursor;
if (s.length() == 0){
return false;
}
if(s.length() == 1){
return hasHexDigits(0,s);
}
if (has_0X_asPrefix(s)){
if (s.length() > 2){
cursor = 2;
}
else {
return false;
}
}
else {
cursor = 0;
}
boolean isHex = hasHexDigits(cursor,s);
return isHex;
}
public static boolean has_0X_asPrefix (String inputStr){
List hexPrefix = Arrays.asList('x', 'X');
return hexPrefix.contains(inputStr.charAt(1)) && (inputStr.charAt(0) == '0');
}
public static boolean hasHexDigits (int cursor, String inputStr){
List hexDigits = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
for (;cursor < inputStr.length(); cursor++){
if (hexDigits.contains(inputStr.charAt(cursor))){
continue;
}
else {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment