Check if a string represents a hexadecimal number or not


In computer science, hexadecimal is a base-16 number system. It uses 16 distinct symbols, including the ten decimal digits from 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 or not.

Problem Statement

Given a string, the task is to check if it represents a valid hexadecimal number or not.

Approach

We can solve this problem by iterating over the characters in the string and checking if they belong to the set of valid hexadecimal characters. The valid hexadecimal characters are digits from 0 to 9 and letters from A to F (in upper or lower case). If all characters in the string belong to this set, then the string represents a valid hexadecimal number.

Example

Here's the C++ code implementation of the above approach −

#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;
}

Output

Running the above code will output

ABCD1234 represents a valid hexadecimal number.
12G4F5 does not represent a valid hexadecimal number.

Time Complexity

The time complexity of the solution is O(N), where N is the length of the string.

Space Complexity

The space complexity of the solution is O(1).

In the above code, we have defined a function isHexadecimal that takes a string as input and returns true if the string represents a valid hexadecimal number, and false otherwise. We have used the isxdigit function to check if each character in the string belongs to the set of valid hexadecimal characters.

Test Case

Let's take two strings s1 = "ABCD1234" and s2 = "12G4F5". The string s1 represents a valid hexadecimal number as all characters in the string belong to the set of valid hexadecimal characters. On the other hand, the string s2 does not represent a valid hexadecimal number as it contains the character 'G' which is not a valid hexadecimal character.

Conclusion

In conclusion, we can easily check if a string represents a valid hexadecimal number or not by iterating over its characters and checking if they belong to the set of valid hexadecimal characters.

Updated on: 17-May-2023

954 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements