#include <stdio.h>
#define INT_SIZE sizeof(int)*8 //32bits
int hightest_bit(unsigned int n) {
int pos = 0;
unsigned int m = n;
while(m) {
m = m>>1;
if(m)
pos ++;
}
return pos;
}
int main() {
int num;
printf("Enter any number: ");
scanf("%d", &num);
hightest_bit(num);
}
// O(n)
-------------------------------------------------------
網路上看說這是二分法 但是真的好難理解阿~~~
int get_highest_bit_position(unsigned char x) {
int n = 7;
if (x == 0) return -1; /* position not found */
if ((x >> 4) == 0) { n = n-4; x=x << 4;}
if ((x >> 6) == 0) { n = n-2; x=x << 2;}
if ((x >> 7) == 0) { n = n-1;}
return n;
}
O(logn) or O(1) ??
有大神能幫我解釋這段代碼嗎??
上面的方法我能理解,但是下面這種說是二分法 我真的看不太懂??
去学一下位运算,搞懂左移右移,差不多就可以看得懂这段代码了。