A non-empty zero-indexed string S consisting of Q characters is given. The period of this string is the smallest positive integer P such that:
\$P ≤ Q/2\$ and \$S[K] = S[K+P]\$ for \$0 ≤ K < Q−P.\$
So for example, for the integers 955,1651 and 102, convert the numbers to binary and the function should return 4,5,-1 respectively.
The function returns -1 if there is no binary period for the given integer.
The int n can be any value between 1 to 99999999
Here is the original code given in the challenge. The Challenge states that by modifying at most 2 lines, in the function solution, the existing bug should be fixed.
Here is my Solution, Can someone please review this?
int solution(int n)
{
int d[30];
int l = 0;
int p;
//convert the integer to binary
while(n > 0)
{
d[l]= n %2 ;
n = n /2;
l++;
}
//compute the length of the resulting binary number
//and that is stored in the variable l
for(p = l/2; p >0; p--){
int ok = 1;
int i;
for(i = 0; i < (l - l/2); i++){
if(d[i] != d[i + p]){
ok = 0;
break;
}
}
if(ok){
return p;
}
}
return -1;
}
int main(int argc, char** argv) {
printf("%d\n",solution(102));
printf("%d\n",solution(955));
printf("%d\n",solution(1651));
return 0;
}
for(i = 0; i < (l - l/2); i++){
should befor(i = 0; i < l-p; i++){
\$\endgroup\$