문제

Given an indexable data structure, say vector = ['a','b','c'] of size n=3 and an int i = 3, I would like to transform the 3 into its n-bit binary representation (011) and return the elements ['b','c'] of the vector. That is, for each 1 in the binary representation, return the element at that location. But how do I talk about 'location' in a binary number? I'm having trouble mapping one idea to the other. Any help appreciated.

도움이 되었습니까?

해결책

Use bit shifting to test every bit of i:

 for(x=0; x<sizeof(int) * 8; x++)
 {
     if((i & (1<<x)) > 0)
     {
        // bit at position x is set in i
        add vector[i];          
     }
 }  

this will result in

011 & 001  = 001 // true
011 & 010 =  010 // true
011 & 100 =  000 // false
.. etc
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top