查找数字 n 是否包含特定数字 k 的最有效方法是什么?

What would be the most efficient way to find if a number n contains a specific number k?

本文关键字:数字 有效 方法 是什么 是否 包含特 查找      更新时间:2023-10-16

假设我的约束是
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++;