⭐算法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;
}
相关推荐
lvxiangyu114 小时前
MPPI 算法证明重构:基于无穷维泛函变分与 KL 散度的构造性推导
算法·重构·最优控制·随机最优控制
2301_818419014 小时前
C++中的解释器模式变体
开发语言·c++·算法
爱学习的大牛1234 小时前
windows tcpview 类似功能 c++
c++
ab1515174 小时前
3.25完成*23、*24、*28、*30、*33、*38、*39、*40
算法
颜酱4 小时前
回溯算法实战练习(3)
javascript·后端·算法
biter down4 小时前
C++11 统一列表初始化+std::initializer_list
开发语言·c++
ShineWinsu5 小时前
爬虫对抗:ZLibrary反爬机制实战分析技术文章大纲
c++
小王不爱笑1325 小时前
G1 GC 的核心基础:Region 模型的补充细节
java·jvm·算法
小王不爱笑1326 小时前
三色标记算法
算法
charlie1145141916 小时前
通用GUI编程技术——Win32 原生编程实战(十六)——Visual Studio 资源编辑器使用指南
开发语言·c++·ide·学习·gui·visual studio·win32