⭐算法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;
}
相关推荐
闻缺陷则喜何志丹19 分钟前
【前后缀分解 排序】B4274 [蓝桥杯青少年组省赛 2023] 数字游戏|普及+
c++·蓝桥杯·排序·洛谷·前后缀分解
m0_7369191019 分钟前
C++中的享元模式变体
开发语言·c++·算法
罗湖老棍子26 分钟前
【 例 1】石子合并(信息学奥赛一本通- P1569)
数据结构·算法·区间dp·区间动态规划·分割合并
wangluoqi43 分钟前
26.2.4练习总结
算法
流㶡1 小时前
逻辑回归实战:从原理到不平衡数据优化(含欠拟合/过拟合诊断与召回率提升)
算法·机器学习·逻辑回归
Tisfy1 小时前
LeetCode 3637.三段式数组 I:一次遍历(三种实现)
算法·leetcode·题解·模拟·数组·遍历·moines
遨游xyz1 小时前
数据结构-哈希表
算法·哈希算法
zho_uzhou1 小时前
c++ imgui implot绘图使用示例 visual studio
开发语言·c++·visual studio
dyyx1111 小时前
C++中的过滤器模式
开发语言·c++·算法
机器视觉知识推荐、就业指导2 小时前
用惯了QTimer定时器,如何快速在纯 C++ 项目中替换?
c++