+ 2
How to check and print how many times '1001' is repeating in a binary string example. Input=10011001001 output=3.
10 Respuestas
+ 8
A good function for this purpose is strstr(str1, str2). It returns a char pointer to the first occurrance of str2 that it finds within str1.
After finding the first match, use the returned pointer+1 as str1 to start the next match. Use a while statement to count how many times it finds a match until the returned pointer is null.
+ 5
RORORZOSO ,
have already done a try that you can show us?
thanks!
+ 3
Search lessons about KMP Algorithm.
+ 2
Brian thank you also 👍
+ 2
RORORZOSO This works I guess:
https://code.sololearn.com/cf6cg97uOekq/?ref=app
+ 2
Jeff.C Yup, you *could* use the single ampersand bitwise operator but that'd only add to the execution time of the program. Here's the corrected expression:
str[i] == '1' && str[i+1] == '0' && str[i+2] == '0' && str[i+3] == '1'
+ 1
fan yu that helps thanks a lot
+ 1
Could you use:
if (string[i]='1')&(string[i+1]='0')&(string[i+2]=0)&(string [i+3]=1):
x+=1
else:
//Not sure about my use of &, might have to check the syntax....
+ 1
G'day Quoi Runtime that seems to work nicely!
What does the while do? Seems to me to only be true when num[max] == 1, so does it skip leading zeros? Does it also set max = len(num)-3?
Do the remaining && get skipped if the first check is false? I know it's a pretty simple algorithm, but you mentioned that it may execute slowly, is there a much better way?
+ 1
Bonjour Jeff.C! The 'max' variable in my code is there so that my code doesn't read any garbage value once there aren't the required number of characters left to read. This way, the 'for' loop halts if there aren't four characters present between num[i] and the last element, inclusive of both. This just speeds up the code a bit (I suppose, check out my modified code).
Regarding the ampersand operator, yup, the rest of the expression is just discarded if the previous one is false. This is what's called as 'short-circuiting'. It makes the code a bit faster