Recently did an online programming assessment, where the question was essentially "search a number for specified integers and increment a count".
My solution was to convert the given number to a string, and then search through the string using a for loop and a switch statement. So basically:
for (int i = 0; i < str.length(); i++;)
{
switch(str[i]) {
case '1':
count++;
break;
case '4':
count++;
break;
case '8':
count++;
break;
// etc
}
}
What I'm wondering is, is this an inefficient way of accomplishing this? I believe the time complexity is O(n), but I could be wrong. If it is inefficient, what is a better solution?
**Edited for clarification, added cases '4' and '8'