C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

数値がC++で指定されたベースにあるかどうかを確認します


数の文字列があるとすると、その数が指定された基数Bのものであるかどうかを確認する必要がありますか?文字列が「101110」、b =2の場合、プログラムはtrueを返します。文字列が「A8F」、ベースが16の場合、それは真になります。

アプローチは非常に簡単です。すべての文字が指定されたベースの記号の範囲内にある場合は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

  1. C++で多数が75で割り切れるかどうかを確認します

    ここでは、数値が75で割り切れるかどうかを確認する方法を説明します。この場合、その数は非常に多い数です。したがって、数値を文字列として入力します。 数値は75で割り切れる、数値が3で割り切れる、また25で割り切れる。桁の合計が3で割り切れる場合、数値は3で割り切れる、最後の2桁が25で割り切れる場合、数値は25で割り切れます。 例 #include <bits/stdc++.h> using namespace std; bool isDiv75(string num){    int n = num.length();    long s

  2. C++で多数が5で割り切れるかどうかを確認します

    ここでは、数値が5で割り切れるかどうかを確認する方法を説明します。この場合、その数は非常に多い数です。したがって、数値を文字列として入力します。 数値が5で割り切れるかどうかを確認するには、5で割り切れるかどうかを確認するには、最後の数値が0または5であることを確認する必要があります。 例 #include <bits/stdc++.h> using namespace std; bool isDiv5(string num){    int n = num.length();    if(num[n - 1] != '5'