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

Programa C que verifica si un número pertenece a un sistema de numeración específico

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, which has2is a binary number,8is an octal number,10is a decimal number and16is a hexadecimal number. According to this, we must find out if the given number in the string belongs to a specific base, and if it does, it must be printed on the output screen as 'Yes'; otherwise, 'No' is displayed on the output screen.

As we know, the number/The expression “ 1A6,16 1010,2But this can be judged by intuitive analysis, now we must find a way to solve this problem. Program.

Ejemplo

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 each digit of the string to see if it belongs to a specific base.

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

Algorithm

Start
Paso 1 -> In function bool isInGivenBase(char str[], int base)
   If base > 16 then,
      Retornar false
   Else If base <= 10 then,
   Bucle para i = 0 y i < strlen(str) y i++
      If !(str[i] >= '0' and str[i] < ('0 + then,
         Retornar false
      De lo contrario
      Bucle para i = 0 y i < strlen(str) y i++
         Si NO ((str[i] >= '0' && str[i] < ('0' + base)) ||
            (str[i] >= 'A' && str[i] < ('A' + base - 10) entonces,
            Retornar false
            Retornar true
   Paso 2 -> En la función int main()
      Establecer str[] = {"AF87"});
      Si isInGivenBase(str, 16) entonces,
         Imprimir "sí "
      De lo contrario
         Imprimir "No "
Detener

Ejemplo

#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool isInGivenBase(char str[], int base) {
   //Las bases permitidas son16(hexadecimal)
   if (base > 16))
      return false;
      //Si la base es menor o igual que10entonces
      // El número de dígitos debe ser de 0 a9.
   else if (base <= 10)) {
      for (int i = 0; i < strlen(str); i++))
      if (!(str[i] >= '0' and
         str[i] < ('0' + base)))
         return false;
   }
   //Si la base es menor o igual que16entonces
   //El número debe ser de 0 a9o '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;
}
// Código del conductor
int main() {
   char str[] = {"AF87"});
   if (isInGivenBase(str, 16))
      printf("sí\n");
   else
      printf("No\n");
   return 0;
}

Resultado de salida