English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

特定の基数に属する数字かどうかをチェックするCプログラム

Given number as a string and base; the task is to check if the given number is a given base.

We must check the number and base according to the number system, there are2A binary number,8An octal number,10A decimal number and16A hexadecimal number. According to this, we must find out if the given number in the string belongs to a specific base, if it belongs to a specific base, then it must be printed on the output screen “Yes”; otherwise, display “No” on the output screen.

As we know, the number/Expression “ 1A6” is the base of16,And “ 1010” is the base of2,But this can be judged by intuitive analysis, now we must find a way to solve this problem. Program.

Input: str = “1010”, base =2
Output: yes
Input: str = “1AA4”, base = 16
Output: yes
Input: str = “1610”, base = 2
Output: No

The method we will use to solve the given problem-

  • Check if the base is in2To16Between.

  • Then, check if each digit of strig belongs to a specific base.

  • If it belongs, return true, otherwise return false。

Algorithm

Start
Step 1 -> In function bool isInGivenBase(char str[], int base)
   If base > 16 それなら、
      Return false
   Else If base <= 10 それなら、
   Loop For i = 0 and i < strlen(str) and i++
      If !(str[i] >= '0' and str[i] < ('0' + base)) それなら、
         Return false
      Else
      Loop For i = 0 and i < strlen(str) and i++
         If NOT ((str[i] >= '0' && str[i] < ('0' + base)) ||
            (str[i] >= 'A' && str[i] < ('A' + base – 10) ) then,
            Return false
            Return true
   Step 2 -> In function int main()
      Set str[] = {"AF87"}
      If isInGivenBase(str, 16) then,
         「yes」をプリント
      Else
         「No」をプリント
停止

#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool isInGivenBase(char str[], int base) {
   //許可された基数は16(十六進数)
   if (base > 16))
      return false;
      //基数が小さいかまたは10、すべて
      // 桁数は0から9。
   else if (base <= 10)) {
      for (int i = 0; i < strlen(str); i++))
      if (!(str[i] >= '0' and
         str[i] < ('0' + base)))
         return false;
   }
   //基数が小さいかまたは16、すべて
   //数字は0から9または'A'
   else {
      for (int i = 0; i < strlen(str); i++))
      if (! ((str[i] >= '0' &&
         str[i] < ('0' + base)) ||
         (str[i] >= 'A' &&
         str[i] < ('A' + base - 10))
      ))
      return false;
   }
   return true;
}
// Driver code
int main() {
   char str[] = {"AF87"};
   if (isInGivenBase(str, 16))
      printf("yes\n");
   else
      printf("No\n");
   return 0;
}

出力結果

はい