Compruebe si una string dada es un código de color hexadecimal válido o no

Dada una string str , la tarea es verificar si la string dada es un código de color hexadecimal HTML o no. Imprima si es así, de lo contrario imprima No.

Ejemplos: 

Entrada: str = “#1AFFa1”
Salida:

Entrada: str = “#F00”
Salida:

Entrada: str = “123456”
Salida: No

 

Enfoque:  un código de color hexadecimal HTML sigue el conjunto de reglas mencionado a continuación: 

  1. Comienza con el símbolo ‘#’ .
  2. Luego le siguen las letras de af , AF y/o dígitos del 0 al 9 .
  3. La longitud del código de color hexadecimal debe ser 6 o 3, excluyendo el símbolo ‘#’ .
  4. Por ejemplo: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF son todos códigos de color hexadecimales válidos.

Ahora, para resolver el problema anterior, siga los pasos a continuación:

  1. Verifique la string str para las siguientes condiciones:
    • Si el primer carácter no es # , devuelve falso .
    • Si la longitud no es 3 o 6 . Si no, devuelve falso .
    • Ahora, verifique todos los caracteres que no sean el primer carácter que sean 0-9 , AF o af .
  2. Si se cumplen todas las condiciones mencionadas anteriormente, devuelva true .
  3. Escriba la respuesta de acuerdo con la observación anterior.

A continuación se muestra la implementación del enfoque anterior:

CPP

// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to validate
// the HTML hexadecimal color code.
bool isValidHexaCode(string str)
{
    if (str[0] != '#')
        return false;
 
    if (!(str.length() == 4 or str.length() == 7))
        return false;
 
    for (int i = 1; i < str.length(); i++)
        if (!((str[i] >= '0' && str[i] <= 9)
              || (str[i] >= 'a' && str[i] <= 'f')
              || (str[i] >= 'A' || str[i] <= 'F')))
            return false;
 
    return true;
}
 
// Driver Code
int main()
{
    string str = "#1AFFa1";
 
    if (isValidHexaCode(str)) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
 
    // Function to validate
    // the HTML hexadecimal color code.
    static boolean isValidHexaCode(String str)
    {
        if (str.charAt(0) != '#')
            return false;
 
        if (!(str.length() == 4 || str.length() == 7))
            return false;
 
        for (int i = 1; i < str.length(); i++)
            if (!((str.charAt(i) >= '0' && str.charAt(i) <= 9)
                || (str.charAt(i) >= 'a' && str.charAt(i) <= 'f')
                || (str.charAt(i) >= 'A' || str.charAt(i) <= 'F')))
                return false;
 
        return true;
    }
     
    // Driver code
    public static void main(String args[])
    {
        String str = "#1AFFa1";
 
        if (isValidHexaCode(str)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Python3

# python program for the above approach
 
# Function to validate
# the HTML hexadecimal color code.
def isValidHexaCode(str):
 
    if (str[0] != '#'):
        return False
 
    if (not(len(str) == 4 or len(str) == 7)):
        return False
 
    for i in range(1, len(str)):
        if (not((str[i] >= '0' and str[i] <= '9') or (str[i] >= 'a' and str[i] <= 'f') or (str[i] >= 'A' or str[i] <= 'F'))):
            return False
 
    return True
 
 
# Driver Code
if __name__ == "__main__":
 
    str = "#1AFFa1"
 
    if (isValidHexaCode(str)):
        print("Yes")
 
    else:
        print("No")
 
    # This code is contributed by rakeshsahni

C#

// C# program for the above approach
using System;
class GFG{
 
    // Function to validate
    // the HTML hexadecimal color code.
    static bool isValidHexaCode(string str)
    {
        if (str[0] != '#')
            return false;
 
        if (!(str.Length == 4 || str.Length == 7))
            return false;
 
        for (int i = 1; i < str.Length; i++)
            if (!((str[i] >= '0' && str[i] <= 9)
                || (str[i] >= 'a' && str[i] <= 'f')
                || (str[i] >= 'A' || str[i] <= 'F')))
                return false;
 
        return true;
    }
     
    // Driver code
    public static void Main()
    {
        string str = "#1AFFa1";
 
        if (isValidHexaCode(str)) {
            Console.Write("Yes");
        }
        else {
            Console.Write("No");
        }
    }
}
// This code is contributed by Samim Hossain Mondal.

Javascript

<script>
       // JavaScript Program to implement
       // the above approach
 
       // Function to validate
       // the HTML hexadecimal color code.
       function isValidHexaCode(str) {
           if (str[0] != '#')
               return false;
 
           if (!(str.length == 4 || str.length == 7))
               return false;
 
           for (let i = 1; i < str.length; i++)
               if (!((str[i].charCodeAt(0) <= '0'.charCodeAt(0) && str[i].charCodeAt(0) <= 9)
                   || (str[i].charCodeAt(0) >= 'a'.charCodeAt(0) && str[i].charCodeAt(0) <= 'f'.charCodeAt(0))
                   || (str[i].charCodeAt(0) >= 'A'.charCodeAt(0) || str[i].charCodeAt(0) <= 'F'.charCodeAt(0))))
                   return false;
 
           return true;
       }
 
       // Driver Code
       let str = "#1AFFa1";
 
       if (isValidHexaCode(str)) {
           document.write("Yes" + '<br>');
       }
       else {
           document.write("No" + '<br>');
       }
 
   // This code is contributed by Potta Lokesh
   </script>
Producción

Yes

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por Code_r y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *