Open In App

Check if a number is in given base or not

Improve
Improve
Like Article
Like
Save
Share
Report

Given a number as a string and a base, check if the given number is in the given base or not.

Examples: 

Input : str = "1010", base = 2
Output : Yes

Input : str = "1015", base = 2
Output : No

Input : str = "AF87", base = 16
Output : Yes

The idea is to one by one check if all digits are in the given base range. If yes, return true, else return false.

Implementation:

C++




// CPP program to check if given
// number is in given base or not.
#include <cstring>
#include <iostream>
using namespace std;
 
bool isInGivenBase(string str, int base)
{
    // Allowed bases are till 16 (Hexadecimal)
    if (base > 16)
    return false;
 
    // If base is below or equal to 10, then all
    // digits should be from 0 to 9.
    else if (base <= 10)
    {
    for (int i = 0; i < str.length(); i++)
        if (!(str[i] >= '0' and
             str[i] < ('0' + base)))
            return false;
    }
 
    // If base is below or equal to 16, then all
    // digits should be from 0 to 9 or from 'A'
    else
    {
    for (int i = 0; i < str.length(); i++)
        if (! ((str[i] >= '0' &&
                str[i] < ('0' + base)) ||                                
                (str[i] >= 'A' &&
                 str[i] < ('A' + base - 10))
            ))                
            return false;
    }
    return true;
}
 
// Driver code
int main()
{
    string str = "AF87";
    if (isInGivenBase(str, 16))
    cout << "Yes";
    else
    cout << "No";
    return 0;
}


Java




// Java program to check if given
// number is in given base or not.
class Geeks {
     
static boolean isInGivenBase(String str, int base)
{
     
    // Allowed bases are till 16 (Hexadecimal)
    if (base > 16)
    return false;
 
    // If base is below or equal to 10, then all
    // digits should be from 0 to 9.
    else if (base <= 10)
    {
    for (int i = 0; i < str.length(); i++)
        if (!(str.charAt(i) >= '0' &&
              str.charAt(i) < ('0' + base)))
            return false;
    }
 
    // If base is below or equal to 16, then all
    // digits should be from 0 to 9 or from 'A'
    else
    {
    for (int i = 0; i < str.length(); i++)
        if (! ((str.charAt(i) >= '0' &&
                str.charAt(i) < ('0' + base)) ||                            
                (str.charAt(i) >= 'A' &&
                 str.charAt(i) < ('A' + base - 10))
            ))            
            return false;
    }
    return true;
}
 
// Driver Class
public static void main(String args[])
 
{
    String str = "AF87";
    if (isInGivenBase(str, 16) == true)
    System.out.println("Yes");
    else
    System.out.println("No");
     
}
}
 
// This code is contributed by ankita_saini


Python3




# Python3 program to check if given
# number is in given base or not.
 
def isInGivenBase(Str, base):
 
    # Allowed bases are till 16 (Hexadecimal)
    if (base > 16):
        return False
 
    # If base is below or equal to 10,
    # then all digits should be from 0 to 9.
    elif (base <= 10):
        for i in range(len(Str)):
            if (Str[i].isnumeric() and
               (ord(Str[i]) >= ord('0') and
                ord(Str[i]) < (ord('0') + base)) == False):
                return False
     
    # If base is below or equal to 16, then all
    # digits should be from 0 to 9 or from 'A'
    else:
        for i in range(len(Str)):
            if (Str[i].isnumeric() and
               ((ord(Str[i]) >= ord('0') and
                 ord(Str[i]) < (ord('0') + base)) or
                (ord(Str[i]) >= ord('A') and
                 ord(Str[i]) < (ord('A') + base - 10))) == False):
                return False
     
    return True
 
# Driver code
Str = "AF87"
if (isInGivenBase(Str, 16)):
    print("Yes")
else:
    print("No")
     
# This code is contributed by Mohit Kumar


C#




// C# program to check if given
// number is in given base or not.
using System;
 
class GFG
{
static bool isInGivenBase(String str,
                          int bas)
{
     
    // Allowed base are
    // till 16 (Hexadecimal)
    if (bas > 16)
    return false;
 
    // If bas is below or equal
    // to 10, then all digits
    // should be from 0 to 9.
    else if (bas <= 10)
    {
    for (int i = 0; i < str.Length; i++)
        if (!(str[i] >= '0' &&
              str[i] < ('0' + bas)))
            return false;
    }
 
    // If base is below or equal
    // to 16, then all digits should
    // be from 0 to 9 or from 'A'
    else
    {
    for (int i = 0; i < str.Length; i++)
        if (! ((str[i] >= '0' &&
                str[i] < ('0' + bas)) ||                        
               (str[i] >= 'A' &&
                str[i] < ('A' + bas - 10))
            ))        
            return false;
    }
    return true;
}
 
// Driver Code
public static void Main(String []args)
{
    String str = "AF87";
    if (isInGivenBase(str, 16) == true)
    Console.WriteLine("Yes");
    else
    Console.WriteLine("No");
}
}
 
// This code is contributed
// by ankita_saini


PHP




<?php
// PHP program to check if given
// number is in given base or not.
 
function isInGivenBase($str, $base)
{
    // Allowed bases are till
    // 16 (Hexadecimal)
    if ($base > 16)
    return false;
 
    // If base is below or equal to
    // 10, then all digits should
    // be from 0 to 9.
    else if ($base <= 10)
    {
    for ($i = 0; $i < strlen($str); $i++)
        if (!($str[$i] >= '0' and
            $str[$i] < ('0' + $base)))
            return false;
    }
 
    // If base is below or equal to 16,
    // then all digits should be from
    // 0 to 9 or from 'A'
    else
    {
    for ($i = 0; $i < strlen($str); $i++)
        if (! (($str[$i] >= '0' &&
                $str[$i] < ('0' + $base)) ||                            
               ($str[$i] >= 'A' &&
                $str[$i] < ('A' + $base - 10))
            ))            
            return false;
    }
    return true;
}
 
// Driver code
$str = "AF87";
 
if (isInGivenBase($str, 16))
    echo "Yes";
else
    echo "No";
 
// This code is contributed by jit_t
?>


Javascript




<script>
 
    // Javascript program to check if given
    // number is in given base or not.
     
    function isInGivenBase(str, bas)
    {
 
        // Allowed base are
        // till 16 (Hexadecimal)
        if (bas > 16)
            return false;
 
        // If bas is below or equal
        // to 10, then all digits
        // should be from 0 to 9.
        else if (bas <= 10)
        {
          for (let i = 0; i < str.length; i++)
              if (!(str[i].charCodeAt() >=
              '0'.charCodeAt() &&
               str[i].charCodeAt() <
               ('0'.charCodeAt() + bas)))
                  return false;
        }
 
        // If base is below or equal
        // to 16, then all digits should
        // be from 0 to 9 or from 'A'
        else
        {
          for (let i = 0; i < str.length; i++)
              if (! ((str[i].charCodeAt() >=
              '0'.charCodeAt() &&
               str[i].charCodeAt() <
               ('0'.charCodeAt() + bas)) ||                        
               (str[i].charCodeAt() >=
               'A'.charCodeAt() &&
                str[i].charCodeAt() <
                ('A'.charCodeAt() + bas - 10))
                  ))        
                  return false;
        }
        return true;
    }
     
    let str = "AF87";
    if (isInGivenBase(str, 16) == true)
        document.write("Yes");
    else
        document.write("No");
 
</script>


Output

Yes

Complexity Analysis:

  • Time complexity: O(n), where n is the length of the given string.
  • Auxiliary Space: O(1)

Approach 2:

Another approach to check whether a given number is valid in a given base is to convert the number to its decimal equivalent, and then convert it back to the given base. If the resulting number is the same as the original number, then the original number is valid in the given base.In this approach, we first convert the given number to its decimal equivalent using the base it’s given in. Then we convert this decimal number back to the given base and compare the result with the original number. If they are the same, we return true; otherwise, we return false.

C++




#include <iostream>
#include <string>
#include <cmath>
using namespace std;
 
int digitToInt(char c) {
    if (c >= '0' && c <= '9')
        return c - '0';
    else
        return c - 'A' + 10;
}
 
char intToDigit(int i) {
    if (i >= 0 && i <= 9)
        return '0' + i;
    else
        return 'A' + i - 10;
}
 
bool isInGivenBase(string str, int base) {
    int decimal = 0;
    int power = 1;
    for (int i = str.length() - 1; i >= 0; i--) {
        int digit = digitToInt(str[i]);
        if (digit >= base)
            return false;
        decimal += digit * power;
        power *= base;
    }
    string converted = "";
    while (decimal > 0) {
        int remainder = decimal % base;
        converted = intToDigit(remainder) + converted;
        decimal /= base;
    }
    return converted == str;
}
 
int main() {
    string str = "AF87";
    if (isInGivenBase(str, 16))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static int digitToInt(char c)
    {
        if (c >= '0' && c <= '9')
            return c - '0';
        else
            return c - 'A' + 10;
    }
    public static char intToDigit(int i)
    {
        if (i >= 0 && i <= 9)
            return (char)('0' + i);
        else
            return (char)('A' + i - 10);
    }
 
    public static boolean isInGivenBase(String str,
                                        int base)
    {
        int decimal = 0;
        int power = 1;
        for (int i = str.length() - 1; i >= 0; i--) {
            int digit = digitToInt(str.charAt(i));
            if (digit >= base)
                return false;
            decimal += digit * power;
            power *= base;
        }
        String converted = "";
        while (decimal > 0) {
            int remainder = decimal % base;
            converted = intToDigit(remainder) + converted;
            decimal /= base;
        }
        return converted.equals(str);
    }
 
    public static void main(String[] args)
    {
        String str = "AF87";
        if (isInGivenBase(str, 16))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}


Python3




def digit_to_int(c):
    if c >= '0' and c <= '9':
        return ord(c) - ord('0')
    else:
        return ord(c) - ord('A') + 10
 
def int_to_digit(i):
    if i >= 0 and i <= 9:
        return chr(ord('0') + i)
    else:
        return chr(ord('A') + i - 10)
 
def is_in_given_base(string, base):
    decimal = 0
    power = 1
    for i in range(len(string) - 1, -1, -1):
        digit = digit_to_int(string[i])
        if digit >= base:
            return False
        decimal += digit * power
        power *= base
    converted = ""
    while decimal > 0:
        remainder = decimal % base
        converted = int_to_digit(remainder) + converted
        decimal //= base
    return converted == string
 
if __name__ == '__main__':
    string = "AF87"
    if is_in_given_base(string, 16):
        print("Yes")
    else:
        print("No")


Javascript




// Function to convert a single digit to an integer
function digitToInt(c) {
    if (c >= '0' && c <= '9')
        return c.charCodeAt(0) - '0'.charCodeAt(0);
    else
        return c.charCodeAt(0) - 'A'.charCodeAt(0) + 10;
}
 
// Function to convert an integer to a single digit
function intToDigit(i) {
    if (i >= 0 && i <= 9)
        return String.fromCharCode('0'.charCodeAt(0) + i);
    else
        return String.fromCharCode('A'.charCodeAt(0) + i - 10);
}
 
// Function to check if a string is in a given base
function isInGivenBase(str, base) {
    let decimal = 0;
    let power = 1;
    for (let i = str.length - 1; i >= 0; i--) {
        let digit = digitToInt(str[i]);
        if (digit >= base)
            return false;
        decimal += digit * power;
        power *= base;
    }
    let converted = "";
    while (decimal > 0) {
        let remainder = decimal % base;
        converted = intToDigit(remainder) + converted;
        decimal = Math.floor(decimal / base);
    }
    return converted == str;
}
 
// Main function
let str = "AF87";
if (isInGivenBase(str, 16))
    console.log("Yes");
else
    console.log("No");


C#




using System;
 
namespace BaseConversionCheck
{
    class Program
    {
        static int DigitToInt(char c)
        {
            if (c >= '0' && c <= '9')
                return c - '0';
            else
                return c - 'A' + 10;
        }
 
        static char IntToDigit(int i)
        {
            if (i >= 0 && i <= 9)
                return (char)('0' + i);
            else
                return (char)('A' + i - 10);
        }
 
        static bool IsInGivenBase(string str, int baseValue)
        {
            int decimalValue = 0;
            int power = 1;
            for (int i = str.Length - 1; i >= 0; i--)
            {
                int digit = DigitToInt(str[i]);
                if (digit >= baseValue)
                    return false;
                decimalValue += digit * power;
                power *= baseValue;
            }
            string converted = "";
            while (decimalValue > 0)
            {
                int remainder = decimalValue % baseValue;
                converted = IntToDigit(remainder) + converted;
                decimalValue /= baseValue;
            }
            return converted == str;
        }
 
        static void Main(string[] args)
        {
            string str = "AF87";
            if (IsInGivenBase(str, 16))
                Console.WriteLine("Yes");
            else
                Console.WriteLine("No");
        }
    }
}


Output

Yes

Complexity Analysis:

Time complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1)
 



Last Updated : 12 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads