檢查一個數字是否在一個給定的進制中(用 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

更新時間:22-Oct-2019

175 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始學習
廣告