
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Number Is in Given Base 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
Advertisements