檢查一個數字是否在一個給定的進制中(用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP