Home > Article > Backend Development > Check if a string represents a hexadecimal number
In computer science, hexadecimal is a 16-based number system. It uses 16 different symbols, including the ten decimal digits 0 to 9 and the six letters A, B, C, D, E and F to represent numbers from 0 to 15. In this article, we will discuss how to check if a string represents a hexadecimal number.
Given a string, the task is to check whether it represents a valid hexadecimal number.
We can solve this problem by iterating the characters in the string and checking if they belong to a valid hex character set. Valid hexadecimal characters are numbers from 0 to 9 and letters from A to F (regardless of uppercase or lowercase). If all characters in the string belong to this character set, then the string represents a valid hexadecimal number.
This is the C code implementation of the above method:
#include <iostream> #include <string> using namespace std; bool isHexadecimal(string s) { int n = s.length(); for (int i = 0; i < n; i++) { if (!isxdigit(s[i])) { return false; } } return true; } int main() { string s1 = "ABCD1234"; string s2 = "12G4F5"; if (isHexadecimal(s1)) { cout << s1 << " represents a valid hexadecimal number." << endl; } else { cout << s1 << " does not represent a valid hexadecimal number." << endl; } if (isHexadecimal(s2)) { cout << s2 << " represents a valid hexadecimal number." << endl; } else { cout << s2 << " does not represent a valid hexadecimal number." << endl; } return 0; }
Running the above code will output
ABCD1234 represents a valid hexadecimal number. 12G4F5 does not represent a valid hexadecimal number.
The time complexity of the solution is O(N), where N is the length of the string.
The space complexity of the solution is O(1).
In the above code, we define a function isHexadecimal, which accepts a string as input and returns true when the string represents a valid hexadecimal number, otherwise it returns false. We use the isxdigit function to check if each character in the string belongs to a valid hexadecimal character set.
Let us take two strings s1 = "ABCD1234" and s2 = "12G4F5". The string s1 represents a valid hexadecimal number because all characters in the string belong to the valid hexadecimal character set. On the other hand, string s2 does not represent a valid hexadecimal number because it contains a character 'G' which is not a valid hexadecimal character.
In summary, we can easily check if a string represents a valid hexadecimal number by iterating over the characters of the string and checking if they belong to a valid hexadecimal character set.
The above is the detailed content of Check if a string represents a hexadecimal number. For more information, please follow other related articles on the PHP Chinese website!