Program to check if a number belongs to a particular base or not
Last Updated :
16 Mar, 2023
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(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[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)
Similar Reads
C Program to Check Whether a Number is Positive or Negative or Zero
Write a C program to check whether a given number is positive, negative, or zero.ExamplesInput: 10Output: PositiveExplanation: Since 10 is greater than 0, it is positive.Input: -5Output: NegativeExplanation: Since -5 is less than 0, it is negative.Different Ways to Check for Positive Numbers, Negati
3 min read
C Program to Check Armstrong Number
An Armstrong number is defined as a number that is equal to the sum of the Kth power of each digit in the number, where K is the number of digits in it.Example:Input: 153Output: YesExplanation: 153 is an Armstrong number of 3 digits, since the sum of cubes of each digit is equal to the number itself
4 min read
C Program to Check for Odd or Even Number
Write a C program to check whether the given number is an odd number or an even number.A number that is completely divisible by 2 is an even number and a number that is not completely divisible by 2 leaving a non-zero remainder is an odd number.ExampleInput: N = 4Output: EvenExplanation: 4 is divisi
4 min read
Program that allows integer input only
Given an input value N, the task is to allow taking only integer input from the user. Now, if the user enters any input other than an integer, that is, a character or symbol, it will not be accepted by the program. Below is the C program to implement this approach: C // C program for the above appro
3 min read
Palindrome Number Program in C
Palindrome numbers are those numbers that remain the same even after reversing the order of their digits. In this article, we will learn how to check whether the given number is a palindrome number using C program.ExamplesInput: 121Output: YesExplanation: The number 121 remains the same when its dig
3 min read
Program to Find Class From Binary IP Address Classful Addressing
An IP address is an important concept in computers and networking. IP address helps each packet which uses routing tables to determine the best route for the packet to take to reach its destination. That makes the Class of an IP address an important concept so let us check how to find a class from a
8 min read
Program to find out the data type of user input
Take a input from user and find out the data type of input value. Examples : Input : geek Output : The input is a string Input : chetna Output : The input is a string Input : 4 Output : The input is a integer Below is C program to find the datatype of user input : C // C program to find data type #i
2 min read
CÂ Program To Check Neon Number
Given a number (num) we need to check whether it is a Neon Number ( i.e. a number where the sum of digits of the square of the number is equal to the number ) and return "true" or "false" accordingly. Example: Input: num = 9 Output: true Explanation: square of 9 is 9 * 9 = 81 , sum of digit of squar
3 min read
Check if a number is a Pangram or not
Given an integer N, the task is to check whether the given number is a pangram or not. Note: A Pangram Number contains every digit [0- 9] at least once. Examples: Input : N = 10239876540022Output : YesExplanation: N contains all the digits from 0 to 9. Therefore, it is a pangram. Input : N = 2345678
7 min read
C++ Program to Check if two numbers are bit rotations of each other or not
Given two positive integers x and y, check if one integer is obtained by rotating bits of other. Input constraint: 0 < x, y < 2^32 Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.More info
3 min read