⭐算法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;
}
相关推荐
做cv的小昊6 分钟前
【TJU】研究生应用统计学课程笔记(6)——第二章 参数估计(2.4 区间估计)
人工智能·笔记·线性代数·算法·机器学习·数学建模·概率论
普贤莲花14 分钟前
【2026年第18周---写于20260501】---舍得
程序人生·算法·leetcode
2zcode14 分钟前
基于深度学习的口腔疾病图像识别系统(UI界面+改进算法+数据集+训练代码)
人工智能·深度学习·算法
Sarvartha23 分钟前
N 个字符串最长公共子序列(LCS)求解问题
数据结构·算法
一切皆是因缘际会23 分钟前
下一代 AI 架构:基于记忆演化与单向投影的安全智能系统
大数据·人工智能·深度学习·算法·安全·架构
falldeep30 分钟前
五分钟了解OpenClaw底层架构
人工智能·算法·机器学习·架构
m0_6294947330 分钟前
LeetCode 热题 100-----16.除了自身以外数组的乘积
数据结构·算法·leetcode
weixin_4462608536 分钟前
模型能力深度对决:GPT-4o、Claude 3.5和DeepSeek V系列模型的横向评测与未来趋势洞察
人工智能·算法·机器学习
晚风吹红霞36 分钟前
C++异常处理核心知识点全解析
开发语言·c++
CoderCodingNo37 分钟前
【信奥业余科普】C++ 的奇妙之旅 | 17:面的铺展与文本的本质——二维数组与字符串
开发语言·c++