在C++中检查一个数字是否在给定的基数
假设我们有一个数字串,我们必须找出这个数是否是给定的基数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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短