⭐算法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;
}
相关推荐
leiming68 分钟前
c++ 容器 queue
开发语言·c++
繁星星繁8 分钟前
【项目】基于SDK实现的智能聊天助手(使用api接入deepseek)------(二)
c++·设计模式·学习方法
车队老哥记录生活10 分钟前
强化学习 RL 基础 3:随机近似方法 | 梯度下降
人工智能·算法·机器学习·强化学习
CSDN_RTKLIB12 分钟前
【类定义系列三】内联函数进阶
开发语言·c++
闲看云起19 分钟前
LeetCode-day2:字母异位词分组分析
算法·leetcode·职场和发展
北京流年24 分钟前
执行clang --version报错说由于找不到 libgcc_s_seh-1.dll和 找不到 libstdc++-6.dll 这两个文件
开发语言·c++
NAGNIP1 小时前
Hugging Face 200页的大模型训练实录
人工智能·算法
Swift社区1 小时前
LeetCode 457 - 环形数组是否存在循环
算法·leetcode·职场和发展
fpcc1 小时前
跟我学C++中级篇—Linux内核中链表分析
linux·c++·链表
挖矿大亨1 小时前
C++中的this指针
java·开发语言·c++