C++ 给定基数下的全数字数
包含从 0 到基数 B 的所有数字的数字称为该基数下的全数字数。但是,有些数字包含 1 到 9 的数字,并被称为无零全数字数。全数字数的一些示例是 0123456789、0789564312 等。
在本教程中,我们将讨论一个问题,其中给定一个数字和一个基数,我们需要检查该数字在给定基数下是否为全数字数,例如 -
Input: num = “9651723467380AZ”, base = 10 Output: YES Explanation: num contains all the digits in the base 10 i.e from 0 to 9, so it is a pandigital number. Input: num = “130264ABCDE745789”, base = 16 Output: NO Explanation: num does not contain F(15) which is in the base 16 i.e from 0 to 15, so it is not a pandigital number.
查找解决方案的方法
为了解决这个问题,我们将使用集合并将每个数字插入集合中,因为我们需要存储唯一值。
遍历字符串,每次取一个字符。
然后检查元素是整数还是字母。
如果它是字母,则将其在字母表中的位置加上 10 以表示两位数。
将值存储在集合中。
遍历后,检查集合的大小是否等于基数。
示例
以上方法的 C++ 代码
#include<bits/stdc++.h> using namespace std; int main(){ int base = 10; char n[] = "9651723467380AZ"; // Declaring set to store unique values. set<int, greater<int> > s; // Traversing through the string. for (int i = 0; i < strlen(n); i++){ // Checking if element is Integer. if (n[i] >= '0' && n[i] <= '9') s.insert(n[i]- '0'); // Checking if element is alphabet. else if (n[i] - 'A' <= base - 11) s.insert(n[i] - 'A' + 10) ; } // Checking if all the digits are present. if(s.size()==base) cout<< "YES"; else cout<< "NO"; return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
YES
结论
在本教程中,我们讨论了一个问题,其中给定一个数字和一个基数。我们需要找到该数字是否为全数字数。我们讨论了一种简单的解决此问题的方法,即在集合中插入值并将其大小与基数进行比较。我们还讨论了此问题的 C++ 程序,我们可以使用 C、Java、Python 等编程语言来实现。希望本教程对您有所帮助。
广告