Check if a number is in given base or not in C++


Suppose, we have a number string, we have to find that the number is of given base B or not? If the string is “101110”, b = 2, then the program will return true. If the string is “A8F”, base is 16, it will be true.

The approach is very simple. If all of the character is in the range of symbols of the given base, then return true, otherwise false.

Example

 Live Demo

#include <iostream>
using namespace std;
bool inGivenBase(string s, int base) {
   if (base > 16) //program can handle upto base 1
      return false;
      else if (base <= 10) { //for 0 to 9
         for (int i = 0; i < s.length(); i++)
            if (!(s[i] >= '0' && s[i] < ('0' + base)))
               return false;
      } else {
         for (int i = 0; i < s.length(); i++)
            if (! ((s[i] >= '0' && s[i] < ('0' + base)) || (s[i] >= 'A' && s[i] < ('A' + base - 10))))
            return false;
      }
   return true;
}
int main() {
   string str = "A87F";
   int base = 16;
   if(inGivenBase(str, base)){
      cout << str << " is in base " << base;
   } else {
      cout << str << " is not in base " << base;
   }
}

Output

A87F is in base 16

Updated on: 22-Oct-2019

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements