当前位置: 首页 > 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;  // 检查最低位是否为 1n >>= 1;         // 右移一位}return count;
}int main() {uint32_t n = 11; // 二进制为 1011cout << "Number of set bits: " << hammingWeight(n) << endl; // 输出 3return 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;
}

http://www.mrgr.cn/news/92684.html

相关文章:

  • 标签使用笔记
  • 图像仿射变换
  • Git快速入门
  • WorldQuant Brain的专属语言——Fast Expression
  • Java中的ArrayDeque
  • vscode集成DeepSeek
  • C++ ++++++++++
  • 一个原教旨的多路径 TCP
  • [C++] enum 以及 enum class 简单用法
  • Java进阶——数据类型深入解析
  • Java进阶——Stream流以及常用方法详解
  • 【漫话机器学习系列】110.线性可分(Linearly Separable)
  • Java进阶——注解一文全懂
  • 查看ITHOR全部仿真家庭场景
  • 阿里云物联网获取设备属性api接口:QueryDevicePropertyData
  • ubuntu离线安装Ollama并部署Llama3.1 70B INT4并对外发布服务
  • FinRobot:一个使用大型语言模型进行金融分析的开源AI代理平台
  • AcWing 5933:爬楼梯 ← 递归 / 递推 / 高精度
  • 本地部署Deepseek+Cherry Studio
  • 自然语言处理(NLP):文本向量化从文字到数字的原理