English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Given number as a string and base; the task is to check if the given number is of the given base.
We must check the number and base according to the number system, which has 2 binary numbers, 8 octal numbers, 10 decimal numbers, and 16 hexadecimal numbers. 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 we must print “Yes” on the output screen; otherwise, display “No” on the output screen.
As we know, the number/expression “1A6” has a base of 16, and “1010” has a base of 2, but this can be judged by intuition 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 between 2 and 16.
Then check each digit of the string to see if it belongs to a specific base.
If it belongs, return true, otherwise return false.
Start Step 1 -> In function bool isInGivenBase(char str[], int base) If base > 16 then, Restituisci false Else If base <= 10 then, Loop For i = 0 and i < strlen(str) and i++ If !(str[i] >= '0' && str[i] < ('0' + base)) then, Restituisci false Altro 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, Restituisci false Restituisci true Passo 2 -> In funzione int main() Imposta str[] = {"AF87"} Se isInGivenBase(str, 16) allora, Stampa "sì" Altro Stampa "No" Ferma
#include <ctype.h> #include <stdio.h> #include <string.h> bool isInGivenBase(char str[], int base) { // La base permessa è 16 (esadecimale) if (base > 16) return false; // Se la base è minore o uguale a 10, tutto // Il numero di cifre dovrebbe essere tra 0 e 9. else if (base <= 10) { for (int i = 0; i < strlen(str); i++) if (!(str[i] >= '0' and str[i] < ('0' + base))) return false; } // Se la base è minore o uguale a 16, tutto // Il numero dovrebbe essere tra 0 e 9 o '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; } // Codice del driver int main() { char str[] = {"AF87"}; if (isInGivenBase(str, 16)) printf("sì\n"); else printf("No\n"); return 0; }
Risultato di output
sì