C語言程式:檢查數字是否屬於特定進位制
給定一個表示數字的字串和一個進位制;任務是檢查給定的數字是否屬於該進位制。
我們需要根據數字系統檢查數字和進位制,其中進位制包括:二進位制為2,八進位制為8,十進位制為10,十六進位制為16。根據此,我們需要找到給定的字串數字是否屬於特定進位制。如果屬於特定進位制,則在輸出螢幕上列印“Yes”;否則列印“No”。
例如,我們知道數字/表示式“1A6”是16進位制,“1010”是2進位制,但這可以透過簡單的視覺分析判斷,現在我們需要找到一種方法來透過程式解決這個問題。
示例
Input: str = “1010”, base =2 Output: yes Input: str = “1AA4”, base = 16 Output: yes Input: str = “1610”, base = 2 Output: No
我們將使用的解決問題的方法 −
- 檢查進位制是否在2到16之間。
- 然後檢查字串的每個數字是否屬於特定進位制。
- 如果屬於,則返回true,否則返回false。
演算法
Start Step 1 -> In function bool isInGivenBase(char str[], int base) If base > 16 then, Return false Else If base <= 10 then, Loop For i = 0 and i < strlen(str) and i++ If !(str[i] >= '0' and str[i] < ('0' + base)) then, 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, Print "yes " Else Print "No " Stop
示例
#include <ctype.h> #include <stdio.h> #include <string.h> bool isInGivenBase(char str[], int base) { // Allowed bases are till 16 (Hexadecimal) if (base > 16) return false; // If base is below or equal to 10, then all // digits should be from 0 to 9. else if (base <= 10) { for (int i = 0; i < strlen(str); i++) if (!(str[i] >= '0' and str[i] < ('0' + base))) return false; } // If base is below or equal to 16, then all // digits should be from 0 to 9 or from '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
"); else printf("No
"); return 0; }
輸出
yes
廣告