查找数字 n 是否包含特定数字 k 的最有效方法是什么?
What would be the most efficient way to find if a number n contains a specific number k?
假设我的约束是
1<=n<=10^90<=k<=9
在最短的时间内搜索它的最佳算法是什么?
为此,我尝试了两种方法:我的第一个方法n 是数字,k 是 4 或 7
while(n>0)
{
d=n%10;
if(d==4 || d==7)
return true;
n/=10;
}
我的第二种方法是将数字转换为字符串并使用查找函数:
string str = NumberToString(i);
if ((str.find("4") != std::string::npos) || (str.find("7") != std::string::npos))
c++;
有没有其他更快的方法来实现这一目标?我所需要的只是数字应该包含 4 或 7
如果您的意思是找到特定数字在数字中出现的次数,那么复杂度将为 O(n),其中 n 是字符串(数字)的长度:
char x = '7';
std::string number("9876541231654810654984431");
int count = 0;
for (size_t i = 0; i < number.size(); ++i)
if (number[i] == x) count++;
相关文章:
- 最高有效数字侧的第N位
- 无符号的 int 到有效数字
- 如何在C++中有效地将数字值重新分配给字符数组
- 将 C 函数转换为 C++ 以检查数字是否有效
- 如何检查用户的输入是否有效以及我正在寻找的数字?
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 如何以更有效的方式检查一个数字是否是素数?
- 有效创建数字签名的正确方法是什么?我可以使用DSA_sign_setup()吗?
- 如何在整数数组中有效地存储大量数字?C++
- 查看数字是否包含在未排序的双数字间隔内的最有效方法?
- 在手臂霓虹灯中有效地重新洗牌和组合 16 个 3 位数字
- 如何有效地找到数字流中元素的等级
- 在向量中找到连续数字的更有效方法
- 我可以在移动平台上有效地使用用C/C 编写的数字算法
- 搜索字符串是否至少包含一次从 0 到 9 的所有数字的最有效方法
- C++:有哪些常规方法可以使代码更有效地用于大数字
- 更有效的方法来制作数字记忆程序
- CIN >> 在较大的数字下失败,但对较小的数字有效?
- 使用一系列数字有效地初始化 std::set