
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Check if a given number is sparse or not in C++
- Check if given number is Emirp Number or not in Python
- Check if the given number is Ore number or not in Python
- Check if a number is a Krishnamurthy Number or not in C++
- Check if a number is jumbled or not in C++
- Check whether a given number is Polydivisible or Not
- Swift Program to Check if the given number is Perfect number or not
- Check if a given matrix is sparse or not in C++
- Check if a given matrix is Hankel or not in C++
- Check if a given graph is tree or not
- Check whether a number has consecutive 0’s in the given base or not using Python
- Check if a number is an Unusual Number or not in C++
- Check if a number is an Achilles number or not in Python
- Check if a number is an Achilles number or not in C++
- C Program to check if a number belongs to a particular base or not

Advertisements