An integer obtained by reversing bits of a given integer A is denoted as bit-rev(A). For example, bit-rev(25) = 19, because binary represenation of 25 is 11001 and after reversing it becomes 10011, i.e. 19. Furthermore, bit-rev(26) = 11 and bit-rev(11) = 13. A symmetric binary root of a given positive integer N is a positive integer A such that N=A*bit-rev(A). For example symmetric binary root of 50 is 10, because 10*bit-rev(10)=10*5=50 . Note that 5 is not a symmetric binary root of 50. Number 286 has two symmetric binary roots: 22 and 26.
Write a function
int symmetric_binary_root_count(int n)
that given a positive integer N returns the smallest symmetric binary root of N. The function should return -1 if N doesn't have any symmetric binary root. Assume that 0
If you like you can use this function for bit-rev (JavaScript):
function bit_rev(n){
var x = n.toString(2).toString(),
arr = [];
for(var i = 0; i< x.length; i++){ arr.push(x.substr(i,1));}
x = arr.reverse().join('');
return parseInt(x,2);
}
Array.prototype.splitis a better alternative than yourfor-loop. – Thomas Eding Aug 15 '11 at 23:28Àssume that 0- that 0 ...? And what is the challenge? You even provide a bitrev-method for javascript. – user unknown Aug 15 '11 at 23:31min_symmetric_binary_root(2n) = 2 min_symmetric_binary_root(n), which allows reducing the problem to finding the minimum symmetric binary root of odd numbers. Since an odd number bit-reverses to an odd number of the same length, this allows working out from the square root and stopping when you pass a power of two. – Peter Taylor Aug 16 '11 at 7:40