⭐算法OJ⭐位操作实战【计数】(C++ 实现)

191. Number of 1 Bits

Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).

cpp 复制代码
int hammingWeight(uint32_t n) {
    int count = 0;
    while (n) {
        count += n & 1;  // 检查最低位是否为 1
        n >>= 1;         // 右移一位
    }
    return count;
}

int main() {
    uint32_t n = 11; // 二进制为 1011
    cout << "Number of set bits: " << hammingWeight(n) << endl; // 输出 3
    return 0;
}

1356. Sort Integers by The Number of 1 Bits

You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.

Return the array after sorting it.

给定一个整数数组 arr,要求按照以下规则对数组进行排序:

  • 按二进制表示中 1 的个数升序排序。
  • 如果两个数的二进制表示中 1 的个数相同,则按数值大小升序排序。

最后返回排序后的数组。

Easy Understanding Version

cpp 复制代码
int countOnes(int num) {
    int count = 0;
    while (num) {
        count += num % 2;
        num = num / 2;
    }
    return count;
}

bool wayToSort(int i, int j) {
    int countA = countOnes(i);
    int countB = countOnes(j);
    if (countA == countB) {
        return i < j;
    }
    return cntA < cntB;
}
vector<int> sortByBits(vector<int>& arr) {
    sort(arr.begin(), arr.end(), wayToSort);
    return arr;
}

Compact Version

cpp 复制代码
int countOnes(int n) {
    return __builtin_popcount(n);  // 计算二进制中 1 的个数
}

vector<int> sortByBits(vector<int>& arr) {
    sort(arr.begin(), arr.end(), [](int a, int b) {
        int countA = countOnes(a);
        int countB = countOnes(b);
        if (countA == countB) {
            return a < b;  // 如果 1 的个数相同,按数值升序排序
        }
        return countA < countB;  // 否则按 1 的个数升序排序
    });
    return arr;
}
相关推荐
程序员弘羽9 分钟前
C++ 第四阶段 内存管理 - 第二节:避免内存泄漏的技巧
java·jvm·c++
爱思德学术21 分钟前
中国计算机学会(CCF)推荐学术会议-B(交叉/综合/新兴):BIBM 2025
算法
冰糖猕猴桃32 分钟前
【Python】进阶 - 数据结构与算法
开发语言·数据结构·python·算法·时间复杂度、空间复杂度·树、二叉树·堆、图
lifallen1 小时前
Paimon vs. HBase:全链路开销对比
java·大数据·数据结构·数据库·算法·flink·hbase
liujing102329292 小时前
Day04_刷题niuke20250703
java·开发语言·算法
DolphinDB2 小时前
如何在C++交易系统中集成高性能回测与模拟撮合
c++
筏.k2 小时前
C++ 网络编程(14) asio多线程模型IOThreadPool
网络·c++·架构
2401_881244402 小时前
Treap树
数据结构·算法
乌萨奇也要立志学C++2 小时前
二叉树OJ题(单值树、相同树、找子树、构建和遍历)
数据结构·算法
网安INF2 小时前
深度学习中的逻辑回归:从原理到Python实现
人工智能·python·深度学习·算法·逻辑回归