Check if a string represents a hexadecimal number or not

Given an alphanumeric string S of length N, the task is to check if the given string represents a hexadecimal number or not. Print Yes if it represents a hexadecimal number. Otherwise, print No.

Examples:

Input: S = “BF57C”
Output: Yes
Explanation:
Decimal Representation of the given string = 783740

Input: S = “58GK”
Output: No

Approach: The approach is based on the idea that all the elements of a hexadecimal number lie between characters A to F or between integers 0 to 9. Below are the steps to solve the problem:

1. Iterate over the given string.
2. Check if each character of the string is between characters A to F or between 0 and 9.
3. If found to be true, then print Yes.
4. Otherwise, print No.

Below is the implementation of the above approach:

C++

 `// C++ implementation of the above approach ``#include ``using` `namespace` `std; ` `// Function to check if the string ``// represents a hexadecimal number ``void` `checkHex(string s) ``{ ``    ` `    ``// Size of string ``    ``int` `n = s.length(); ` `    ``// Iterate over string ``    ``for``(``int` `i = 0; i < n; i++) ``    ``{ ``        ``char` `ch = s[i]; ` `        ``// Check if the character ``        ``// is invalid ``        ``if` `((ch < ``'0'` `|| ch > ``'9'``) && ``            ``(ch < ``'A'` `|| ch > ``'F'``)) ``        ``{ ``            ``cout << ``"No"` `<< endl; ``            ``return``; ``        ``} ``    ``} ` `    ``// Print true if all ``    ``// characters are valid ``    ``cout << ``"Yes"` `<< endl; ``} ` `// Driver code     ``int` `main() ``{ ``    ` `    ``// Given string ``    ``string s = ``"BF57C"``; ` `    ``// Function call ``    ``checkHex(s); ` `    ``return` `0; ``} ` `// This code is contributed by divyeshrabadiya07`

Java

 `// Java implementation of the above approach` `import` `java.util.*;``import` `java.io.*;` `class` `GFG {` `    ``// Function to check if the string``    ``// represents a hexadecimal number``    ``public` `static` `void` `checkHex(String s)``    ``{``        ``// Size of string``        ``int` `n = s.length();` `        ``// Iterate over string``        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``char` `ch = s.charAt(i);` `            ``// Check if the character``            ``// is invalid``            ``if` `((ch < ``'0'` `|| ch > ``'9'``)``                ``&& (ch < ``'A'` `|| ch > ``'F'``)) {` `                ``System.out.println(``"No"``);``                ``return``;``            ``}``        ``}` `        ``// Print true if all``        ``// characters are valid``        ``System.out.println(``"Yes"``);``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``// Given string``        ``String s = ``"BF57C"``;` `        ``// Function Call``        ``checkHex(s);``    ``}``}`

Python3

 `# Python3 implementation of the``# above approach ` `# Function to check if the string``# represents a hexadecimal number``def` `checkHex(s):``  ` `    ``# Iterate over string``    ``for` `ch ``in` `s:` `        ``# Check if the character``        ``# is invalid``        ``if` `((ch < ``'0'` `or` `ch > ``'9'``) ``and``            ``(ch < ``'A'` `or` `ch > ``'F'``)):``                ` `            ``print``(``"No"``)``            ``return``        ` `    ``# Print true if all``    ``# characters are valid``    ``print``(``"Yes"``)` `# Driver Code``    ` `# Given string``s ``=` `"BF57C"`` ` `# Function call``checkHex(s)` `# This code is contributed by extragornax`

C#

 `// C# implementation of ``// the above approach``using` `System;``class` `GFG{` `// Function to check if the string``// represents a hexadecimal number``public` `static` `void` `checkHex(String s)``{``  ``// Size of string``  ``int` `n = s.Length;` `  ``// Iterate over string``  ``for` `(``int` `i = 0; i < n; i++) ``  ``{``    ``char` `ch = s[i];` `    ``// Check if the character``    ``// is invalid``    ``if` `((ch < ``'0'` `|| ch > ``'9'``) && ``        ``(ch < ``'A'` `|| ch > ``'F'``)) ``    ``{``      ``Console.WriteLine(``"No"``);``      ``return``;``    ``}``  ``}` `  ``// Print true if all``  ``// characters are valid``  ``Console.WriteLine(``"Yes"``);``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``  ``// Given string``  ``String s = ``"BF57C"``;` `  ``// Function Call``  ``checkHex(s);``}``}` `// This code is contributed by gauravrajput1`

Javascript

 ``

Output
```Yes

```

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach 2:

Approach:

We can use the built-in function int() with a base of 16 to convert the string to a hexadecimal number. If the conversion is successful, the input string represents a hexadecimal number.

• The input string s is passed as a parameter to the function.
• The int() function is called with the input string s and a base of 16 as its parameters. This function converts a string representation of a number into an integer.
• If the conversion is successful, the function returns True, indicating that the input string represents a hexadecimal number.
• If the conversion raises a ValueError, the function returns False, indicating that the input string does not represent a hexadecimal number. The ValueError is raised when the input string contains characters that are not valid hexadecimal digits.

C++

 `#include ``#include ``#include ` `bool` `isHexadecimal(``const` `std::string& s) {``    ``try` `{``        ``// Attempt to parse the string as an integer in base 16 (hexadecimal)``        ``std::istringstream stream(s);``        ``unsigned ``int` `value;``        ``stream >> std::hex >> value;``        ``return` `!stream.fail(); ``// If successful, the string is hexadecimal``    ``} ``catch` `(std::exception& e) {``        ``return` `false``; ``// If an exception is caught, the string is not hexadecimal``    ``}``}` `int` `main() {``    ``std::string s1 = ``"BF57C"``;``    ``if` `(isHexadecimal(s1)) {``        ``std::cout << ``"Yes"` `<< std::endl;``        ``std::istringstream stream(s1);``        ``unsigned ``int` `value;``        ``stream >> std::hex >> value;``        ``std::cout << ``"Decimal Representation of the given string = "` `<< value << std::endl;``    ``} ``else` `{``        ``std::cout << ``"No"` `<< std::endl;``    ``}` `    ``std::string s2 = ``"58GK"``;``    ``if` `(isHexadecimal(s2)) {``        ``std::cout << ``"Yes"` `<< std::endl;``        ``std::istringstream stream(s2);``        ``unsigned ``int` `value;``        ``stream >> std::hex >> value;``        ``std::cout << ``"Decimal Representation of the given string = "` `<< value << std::endl;``    ``} ``else` `{``        ``std::cout << ``"No"` `<< std::endl;``    ``}` `    ``return` `0;``}`

Java

 `public` `class` `HexadecimalValidator {``    ``// Function to check if a string is a valid hexadecimal representation``    ``public` `static` `boolean` `isHexadecimal(String s) {``        ``try` `{``            ``// Attempt to parse the string as an integer in base 16 (hexadecimal)``            ``Integer.parseInt(s, ``16``);``            ``return` `true``; ``// If successful, the string is hexadecimal``        ``} ``catch` `(NumberFormatException e) {``            ``return` `false``; ``// If an exception is caught, the string is not hexadecimal``        ``}``    ``}` `    ``public` `static` `void` `main(String[] args) {``        ``String s1 = ``"BF57C"``;``        ``if` `(isHexadecimal(s1)) {``            ``System.out.println(``"Yes"``);``            ``System.out.println(``"Decimal Representation of the given string = "` `+ Integer.parseInt(s1, ``16``));``        ``} ``else` `{``            ``System.out.println(``"No"``);``        ``}` `        ``String s2 = ``"58GK"``;``        ``if` `(isHexadecimal(s2)) {``            ``System.out.println(``"Yes"``);``            ``System.out.println(``"Decimal Representation of the given string = "` `+ Integer.parseInt(s2, ``16``));``        ``} ``else` `{``            ``System.out.println(``"No"``);``        ``}``    ``}``}`

Python3

 `def` `is_hexadecimal_1(s):``    ``try``:``        ``int``(s, ``16``)``        ``return` `True``    ``except` `ValueError:``        ``return` `False` `s1 ``=` `"BF57C"``if` `is_hexadecimal_1(s1):``    ``print``(``"Yes"``)``    ``print``(``"Decimal Representation of the given string = {}"``.``format``(``int``(s1, ``16``)))``else``:``    ``print``(``"No"``)` `s2 ``=` `"58GK"``if` `is_hexadecimal_1(s2):``    ``print``(``"Yes"``)``    ``print``(``"Decimal Representation of the given string = {}"``.``format``(``int``(s2, ``16``)))``else``:``    ``print``(``"No"``)`

C#

 `// C# code for the above approach``using` `System;` `public` `class` `GFG {``    ``// Function to check if a string is in hexadecimal``    ``// format``    ``public` `static` `bool` `IsHexadecimal(``string` `s)``    ``{``        ``try` `{``            ``// Attempt to parse the string as an integer in``            ``// base 16 (hexadecimal)``            ``_ = Convert.ToInt32(s, 16);``            ``return` `true``; ``// If successful, the string is``                         ``// hexadecimal``        ``}``        ``catch` `(Exception) {``            ``return` `false``; ``// If an exception is caught, the``                          ``// string is not hexadecimal``        ``}``    ``}` `    ``// Main method``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``string` `s1 = ``"BF57C"``;``        ``if` `(IsHexadecimal(s1)) {``            ``Console.WriteLine(``"Yes"``);``            ``int` `value = Convert.ToInt32(s1, 16);``            ``Console.WriteLine(``                ``"Decimal Representation of the given string = "``                ``+ value);``        ``}``        ``else` `{``            ``Console.WriteLine(``"No"``);``        ``}` `        ``string` `s2 = ``"58GK"``;``        ``if` `(IsHexadecimal(s2)) {``            ``Console.WriteLine(``"Yes"``);``            ``int` `value = Convert.ToInt32(s2, 16);``            ``Console.WriteLine(``                ``"Decimal Representation of the given string = "``                ``+ value);``        ``}``        ``else` `{``            ``Console.WriteLine(``"No"``);``        ``}``    ``}``}` `// This code is contributed by Susobhan Akhuli`

Javascript

 `function` `isHexadecimal(s) {``    ``try` `{``        ``// Attempt to parse the string as an integer in base 16 (hexadecimal)``        ``let value = parseInt(s, 16);``        ``return` `!isNaN(value); ``// If successful, the string is hexadecimal``    ``} ``catch` `(e) {``        ``return` `false``; ``// If an exception is caught, the string is not hexadecimal``    ``}``}` `let s1 = ``"BF57C"``;``if` `(isHexadecimal(s1)) {``    ``console.log(``"Yes"``);``    ``let value = parseInt(s1, 16);``    ``console.log(``"Decimal Representation of the given string ="``, value);``} ``else` `{``    ``console.log(``"No"``);``}` `let s2 = ``"58GK"``;``if` `(isHexadecimal(s2)) {``    ``console.log(``"Yes"``);``    ``let value = parseInt(s2, 16);``    ``console.log(``"Decimal Representation of the given string ="``, value);``} ``else` `{``    ``console.log(``"No"``);``}`

Output
```Yes
Decimal Representation of the given string = 783740
No

```

Time Complexity: O(n)
Space Complexity: O(1)

Previous
Next