Friday, July 5, 2024
HomeData ModellingData Structure & AlgorithmProgram to check if a number belongs to a particular base or...

Program to check if a number belongs to a particular base or not

TiGiven a number N and its radix base R, find whether its valid or not according to its radix base. 
Find valid/invalid number for any base ranging from binary to base32. 

Examples: 

Input : 1000101010001
Output : Valid
1000101010001 is valid binary number.

Input : 0xFFFAG
Output : invalid
0xFFFAG is not a valid hexa-decimal number because of character 'G' .

Method used : strspn

  • strspn :
strspn(numStr, validNumber)
Strspan: 
returns number of matching digits from 
character-set provided, so here it will return 1 - N,
where N is length of validNumber String.
numStr[]  : 
And that number is provided to numStr[] array.
  • numStr : 
numStr[strspn(numStr, validNumber)]
Using this number as index for numStr[] array,
we access the digit there and it will be NULL 
in case string is matched and it will be non-zero 
if string is not matched
  • !numStr : And Finally we invert the result using invert operator to match for true case ! 
!numStr[strspn(numStr, validNumber)]

C++




// Program to check if a number belongs
// to particular base or not#include
 
#include <cstdio>
#include <cstdlib>
#include <cstring>
 
#define BINARY_BASE 2 // Defining binary base
#define OCTAL_BASE 8 // Defining octal base
#define DECIMAL_BASE 10 // Defining decimal base
#define HEXA_BASE 16 // Defining hexa-decimal base
#define BASE32_BASE 32 // Defining base32 base
 
// Function prototypes
bool isValid(const char* numStr, int base);
const char* print(bool status);
 
// Main method for base check
int main(void)
{
    // Defining valid/invalid numbers in radix bases
    char* binaryStr = "1000101010001";
    char* decimalStr = "45221";
    char* base32Str = "AD22F";
 
    // invalid
    char* octalStr = "7778A";
    char* hexStr = "FAG463";
 
    // Printing status of radix bases
    printf("Binary string %s is %s\n", binaryStr,
           print(isValid(binaryStr, BINARY_BASE)));
    printf("Octal string %s is %s\n", octalStr,
           print(isValid(hexStr, OCTAL_BASE)));
    printf("Decimal string %s is %s\n", decimalStr,
           print(isValid(decimalStr, DECIMAL_BASE)));
    printf("Hex string %s is %s\n", hexStr,
           print(isValid(hexStr, HEXA_BASE)));
    printf("Base32 string %s is %s\n", base32Str,
           print(isValid(base32Str, BASE32_BASE)));
 
    return 0;
}
 
bool isValid(const char* numStr, int base)
{
    // Defining valid base strings
    const char* validBinary = "01";
    const char* validOctal = "01234567";
    const char* validDecimal = "0123456789";
    const char* validHex = "0123456789abcdefABCDEF";
    const char* validBase32 = "0123456789abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUV";
    const char* validNumber = NULL;
 
    // Checking for valid base
    validNumber = (base == BINARY_BASE)
                      ? validBinary
                      : ((base == OCTAL_BASE)
                             ? validOctal
                             : (base == DECIMAL_BASE)
                                   ? validDecimal
                                   : (base == HEXA_BASE)
                                         ? validHex
                                         : (base == BASE32_BASE)
                                               ? validBase32
                                               : NULL);
 
    // Error checking for invalid base
    if (validNumber == NULL) {
        fputs("Invalid base encountered", stderr);
        exit(EXIT_FAILURE);
    }
 
    // Check for valid base string using strspn
    return (!numStr[strspn(numStr, validNumber)]) ? true : false;
}
 
const char* print(bool status)
{
    return (status) ? "Valid" : "Invalid";
}


Java




import java.util.*;
 
public class BaseChecker {
    private static final int BINARY_BASE = 2;
    private static final int OCTAL_BASE = 8;
    private static final int DECIMAL_BASE = 10;
    private static final int HEXA_BASE = 16;
    private static final int BASE32_BASE = 32;
 
    public static void main(String[] args) {
        // Defining valid/invalid numbers in radix bases
        String binaryStr = "1000101010001";
        String decimalStr = "45221";
        String base32Str = "AD22F";
 
        // invalid
        String octalStr = "7778A";
        String hexStr = "FAG463";
 
        // Printing status of radix bases
        System.out.printf("Binary string %s is %s\n", binaryStr,
                print(isValid(binaryStr, BINARY_BASE)));
        System.out.printf("Octal string %s is %s\n", octalStr,
                print(isValid(hexStr, OCTAL_BASE)));
        System.out.printf("Decimal string %s is %s\n", decimalStr,
                print(isValid(decimalStr, DECIMAL_BASE)));
        System.out.printf("Hex string %s is %s\n", hexStr,
                print(isValid(hexStr, HEXA_BASE)));
        System.out.printf("Base32 string %s is %s\n", base32Str,
                print(isValid(base32Str, BASE32_BASE)));
    }
 
    private static boolean isValid(String numStr, int base) {
        // Defining valid base strings
        String validBinary = "01";
        String validOctal = "01234567";
        String validDecimal = "0123456789";
        String validHex = "0123456789abcdefABCDEF";
        String validBase32 = "0123456789abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUV";
        String validNumber = null;
 
        // Checking for valid base
        if (base == BINARY_BASE) {
            validNumber = validBinary;
        } else if (base == OCTAL_BASE) {
            validNumber = validOctal;
        } else if (base == DECIMAL_BASE) {
            validNumber = validDecimal;
        } else if (base == HEXA_BASE) {
            validNumber = validHex;
        } else if (base == BASE32_BASE) {
            validNumber = validBase32;
        } else {
            throw new IllegalArgumentException("Invalid base encountered");
        }
 
        // Check for valid base string using a loop
        for (int i = 0; i < numStr.length(); i++) {
            if (validNumber.indexOf(numStr.charAt(i)) == -1) {
                return false;
            }
        }
        return true;
    }
 
    private static String print(boolean status) {
        return (status) ? "Valid" : "Invalid";
    }
}


Python3




BINARY_BASE = 2
OCTAL_BASE = 8
DECIMAL_BASE = 10
HEXA_BASE = 16
BASE32_BASE = 32
 
def is_valid(num_str, base):
    # Defining valid base strings
    valid_binary = "01"
    valid_octal = "01234567"
    valid_decimal = "0123456789"
    valid_hex = "0123456789abcdefABCDEF"
    valid_base32 = "0123456789abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUV"
     
    # Checking for valid base
    valid_number = None
    if base == BINARY_BASE:
        valid_number = valid_binary
    elif base == OCTAL_BASE:
        valid_number = valid_octal
    elif base == DECIMAL_BASE:
        valid_number = valid_decimal
    elif base == HEXA_BASE:
        valid_number = valid_hex
    elif base == BASE32_BASE:
        valid_number = valid_base32
    else:
        raise ValueError("Invalid base encountered")
     
    # Check for valid base string using set intersection
    return set(num_str).issubset(set(valid_number))
 
# Main method for base check
if __name__ == "__main__":
    # Defining valid/invalid numbers in radix bases
    binary_str = "1000101010001"
    decimal_str = "45221"
    base32_str = "AD22F"
 
    # invalid
    octal_str = "7778A"
    hex_str = "FAG463"
 
    # Printing status of radix bases
    print(f"Binary string {binary_str} is {'Valid' if is_valid(binary_str, BINARY_BASE) else 'Invalid'}")
    print(f"Octal string {octal_str} is {'Valid' if is_valid(hex_str, OCTAL_BASE) else 'Invalid'}")
    print(f"Decimal string {decimal_str} is {'Valid' if is_valid(decimal_str, DECIMAL_BASE) else 'Invalid'}")
    print(f"Hex string {hex_str} is {'Valid' if is_valid(hex_str, HEXA_BASE) else 'Invalid'}")
    print(f"Base32 string {base32_str} is {'Valid' if is_valid(base32_str, BASE32_BASE) else 'Invalid'}")


C#




using System;
 
public class BaseChecker
{
  private const int BINARY_BASE = 2;
  private const int OCTAL_BASE = 8;
  private const int DECIMAL_BASE = 10;
  private const int HEXA_BASE = 16;
  private const int BASE32_BASE = 32;
  public static void Main()
  {
     
    // Defining valid/invalid numbers in radix bases
    string binaryStr = "1000101010001";
    string decimalStr = "45221";
    string base32Str = "AD22F";
 
    // invalid
    string octalStr = "7778A";
    string hexStr = "FAG463";
 
    // Printing status of radix bases
    Console.WriteLine($"Binary string {binaryStr} is {Print(IsValid(binaryStr, BINARY_BASE))}");
    Console.WriteLine($"Octal string {octalStr} is {Print(IsValid(octalStr, OCTAL_BASE))}");
    Console.WriteLine($"Decimal string {decimalStr} is {Print(IsValid(decimalStr, DECIMAL_BASE))}");
    Console.WriteLine($"Hex string {hexStr} is {Print(IsValid(hexStr, HEXA_BASE))}");
    Console.WriteLine($"Base32 string {base32Str} is {Print(IsValid(base32Str, BASE32_BASE))}");
  }
 
  private static bool IsValid(string numStr, int baseValue)
  {
    // Defining valid base strings
    string validBinary = "01";
    string validOctal = "01234567";
    string validDecimal = "0123456789";
    string validHex = "0123456789abcdefABCDEF";
    string validBase32 = "0123456789abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUV";
    string validNumber = null;
 
    // Checking for valid base
    switch (baseValue)
    {
      case BINARY_BASE:
        validNumber = validBinary;
        break;
      case OCTAL_BASE:
        validNumber = validOctal;
        break;
      case DECIMAL_BASE:
        validNumber = validDecimal;
        break;
      case HEXA_BASE:
        validNumber = validHex;
        break;
      case BASE32_BASE:
        validNumber = validBase32;
        break;
      default:
        throw new ArgumentException("Invalid base encountered");
    }
 
    // Check for valid base string using a loop
    for (int i = 0; i < numStr.Length; i++)
    {
      if (validNumber.IndexOf(numStr[i]) == -1)
      {
        return false;
      }
    }
    return true;
  }
 
  private static string Print(bool status)
  {
    return (status) ? "Valid" : "Invalid";
  }
}


Javascript




const BINARY_BASE = 2;
const OCTAL_BASE = 8;
const DECIMAL_BASE = 10;
const HEXA_BASE = 16;
const BASE32_BASE = 32;
 
// Function to check if a number is valid in a particular base
function isValid(numStr, base) {
  const validBinary = '01';
  const validOctal = '01234567';
  const validDecimal = '0123456789';
  const validHex = '0123456789abcdefABCDEF';
  const validBase32 = '0123456789abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUV';
  let validNumber = null;
 
  switch (base) {
    case BINARY_BASE:
      validNumber = validBinary;
      break;
    case OCTAL_BASE:
      validNumber = validOctal;
      break;
    case DECIMAL_BASE:
      validNumber = validDecimal;
      break;
    case HEXA_BASE:
      validNumber = validHex;
      break;
    case BASE32_BASE:
      validNumber = validBase32;
      break;
    default:
      console.error('Invalid base encountered');
      return false;
  }
 
  return numStr.split('').every(c => validNumber.indexOf(c) !== -1);
}
 
// Function to print the validity status of a number
function print(status) {
  return status ? 'Valid' : 'Invalid';
}
 
// Main method
function main() {
  // Defining valid/invalid numbers in radix bases
  const binaryStr = '1000101010001';
  const decimalStr = '45221';
  const base32Str = 'AD22F';
 
  // invalid
  const octalStr = '7778A';
  const hexStr = 'FAG463';
 
  // Printing status of radix bases
  console.log(`Binary string ${binaryStr} is ${print(isValid(binaryStr, BINARY_BASE))}`);
  console.log(`Octal string ${octalStr} is ${print(isValid(hexStr, OCTAL_BASE))}`);
  console.log(`Decimal string ${decimalStr} is ${print(isValid(decimalStr, DECIMAL_BASE))}`);
  console.log(`Hex string ${hexStr} is ${print(isValid(hexStr, HEXA_BASE))}`);
  console.log(`Base32 string ${base32Str} is ${print(isValid(base32Str, BASE32_BASE))}`);
}
 
main();


Output: 

Binary string 1000101010001 is Valid
Octal string 7778A is Invalid
Decimal string 45221 is Valid
Hex string FAG463 is Invalid
Base32 string AD22F is Valid                                                                                         

Time complexity: O(1)
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments