codility2

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.

For example, 8 is the period of "codilitycodilityco".

A positive integer M is the binary period of a positive integer N if M is the period of the binary representation of N.

For example, 4 is the binary period of 955, because the binary representation of 955 is "1110111011" and its period is 4. On the other hand, 102 does not have a binary period, because its binary representation is "1100110" and it does not have a period.

Write a function:

int solution(int N);

that, given a positive integer N, returns the binary period of N. The function should return −1 if N does not have a binary period.

For example, given N = 955 the function should return 4, and given N = 102 the function should return −1, as explained in the example above.

Assume that:

  • N is an integer within the range [1..1,000,000,000].

Complexity:

  • expected worst-case time complexity is O(log(N)2);
  • expected worst-case space complexity is O(log(N)).
// you can also use imports, for example:
// #import
int solution(int N) {
    // write your code in Objective-C 2.0
    int numBits = 0;
int temp = N;
while(temp){
numBits++;
temp = temp>>1;
}

for(int i=1; i<=numBits/2; i++){
int a = N>>(numBits%i);
int b = N>>(numBits%i+i);

if(!((a&b)^b)){
return i;
}
}
    
return -1;
    
    
}

你可能感兴趣的:(ios)