guodongxiaren / OJ

4 stars 3 forks source link

二进制有关的简单题 #24

Open guodongxiaren opened 4 years ago

guodongxiaren commented 4 years ago

判断数字是否是2的幂

int power_of_2(int n) {
     return !((n-1) & n);
}
guodongxiaren commented 4 years ago

不用循环统计自然数中数字个数

int count_digit(long n) {
    return floor(log10(n)) + 1;
}
guodongxiaren commented 4 years ago

判断二进制中1的个数

int hammingWeight(uint32_t n) {
    int num = 0;
    while (n) {
        n &= (n-1);
        num++;
    }
    return num;
}