숫자 문자열이 있다고 가정하고 숫자가 주어진 기본 B인지 찾아야합니까? 문자열이 "101110"이고 b =2이면 프로그램은 true를 반환합니다. 문자열이 "A8F"이고 밑이 16이면 true입니다.
접근 방식은 매우 간단합니다. 모든 문자가 지정된 기본 기호 범위에 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.
예시
#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;
}
} 출력
A87F is in base 16