当前位置: 首页 > news >正文

⭐算法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).

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

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

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.简单循环神经网络
  • YOLOv5 + SE注意力机制:提升目标检测性能的实践
  • Distilling the Knowledge in a Neural Network(提炼神经网络中的知识)
  • 15.13 AdaLoRA自适应权重矩阵微调:动态秩调整的智能革命
  • 双机热备旁挂组网实验
  • < 自用文儿 > Gobuster 暴力扫描工具与 SecLists 安全测试词表集合
  • VMware虚拟机配置桥接网络
  • 【前端基础】Day 5 CSS浮动
  • 力扣——颜色分类
  • 【prometheus】Pushgateway安装和使用
  • QT——c++界面编程库
  • yolov8,yolo11,yolo12 服务器训练到部署全流程 笔记
  • 鸿蒙ArkTs开发,后台触发数据变化后更新页面 UI事件
  • 【折线图 Line】——1
  • 影刀RPA中级案例总结
  • 运维Apache面试题及参考答案
  • 17 款电脑压缩工具详解及下载指南(2025 年最新版)
  • Express + MongoDB 实现文件上传
  • ‌Debian 包版本号比较规则详解
  • c++中初始化列表的使用
  • 怎么做视频网站首页/资源搜索引擎
  • 做网站的费用是多少/东莞网站推广策划
  • 建设内部网站目的/2023年适合小学生的新闻
  • wordpress修改文章字体大小/网站seo李守洪排名大师
  • 济南外贸网站/今日山东新闻头条
  • node做网站后台/qq推广官网