zoukankan      html  css  js  c++  java
  • {面试题10: 二进制中1的个数}

    From 剑指Offer 何海涛 著

    #include <iostream>
    using namespace std;
    
    int numberOf1(int n) {
        unsigned int newN = static_cast<unsigned int>(n); // 强制将 n 转换为一个无符号数, 避免负数左移, 产生死循环
        int count = 0;
        while(newN) {
            if(newN&1) {
                count++;
            }
            newN >>= 1;
        }
        return count;
    }
    
    int NumberOf1(int n) {
        int count = 0;
        while(n) {
            count++;
            n &= n-1; // 将 n 最右侧的 1 消耗掉
        }
        return count;
    }

    测试集:

    void test(int n, int expected) {
        std::cout << std::boolalpha << (numberOf1(n) == expected) << std::endl;
        std::cout << std::boolalpha << (NumberOf1(n) == expected) << std::endl;
    }
    int main(int argc, char* argv[]) {
        test(0, 0);
        test(1, 1);
        test(10, 2);
        test(0x7fffffff, 31);
        test(0xffffffff, 32);
        test(0x80000000, 1);
    
        return 0;
    }

    总结:

    1. 判断一个数 n 是否是 2 的幂?

    (n != 0) && ((n & (n-1)) == 0)

    2. 求不小于 n 的 2 的幂?

    if(n>=1) {
        --n;
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;
        ++n;
    }
  • 相关阅读:
    《构建之法阅读笔记02》
    《人月神话阅读笔记01》
    第四周学习进度条
    子数组2
    敏捷开发方法综述
    子数组1
    第三周学习进度条
    四则运算3
    第二周学习进度条
    四则运算4
  • 原文地址:https://www.cnblogs.com/long3216/p/4442446.html
Copyright © 2011-2022 走看看