检查给定数字是否可以用 C++ 中的任意基数表示为给定数字位数
假设我们有一个数字 n 和数字位数 d。我们必须检查数字 n 是否可以用 2 到 32 之间的任何基数表示为 d 位数字。假设数字 n 为 8,d 为 4,则它可以表示为二进制的 1000,此处 d 为 4。
这个想法是从 2 到 32 一一检查所有基数。我们可以遵循以下步骤来检查基数。
- 如果数字小于基数,并且数字位数为 1,则返回 true
- 如果数字位数大于 1 且数字大于基数,则通过执行 num/base 从数字中删除最后一位,从而减少数字位数,然后反复递归执行此操作。
- 否则返回 false。
示例
#include <iostream>
using namespace std;
bool isRepresentedInDDigits(int num, int d, int base) {
if (d==1 && num < base)
return true;
if (d > 1 && num >= base)
return isRepresentedInDDigits(num/base, --d, base);
return false;
}
bool checkNumber(int num, int d) {
// Check for all bases one by one
for (int base=2; base<=32; base++)
if (isRepresentedInDDigits(num, d, base))
return true;
return false;
}
int main() {
int num = 8;
int dig = 2;
if(checkNumber(num, dig))
cout << "Can be represented";
else
cout << "Can not be represented";
}输出
Can be represented
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP