-9

Assuming my constraints are
1<=n<=10^9 0<=k<=9

What would be the best algorithm to search this in minimum time?

I have tried 2 methods for this: My first method n is the number and k is 4 or 7

while(n>0)
 {
         d=n%10;
         if(d==4 || d==7)
         return true;
         n/=10;
 }

My second method im converting the number to a string and using the find function:

string str = NumberToString(i);
if ((str.find("4") != std::string::npos) || (str.find("7") != std::string::npos))
 c++;  

Is there another faster way to achieve this? All i need is that the number should contain 4 or 7

4

1 回答 1

1

如果计算一个特定数字在一个数字中出现的次数是你的意思,那么复杂度将是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++;
于 2013-10-04T15:19:50.093 回答