您的位置:首页 > 汽车 > 新车 > 宁波网站开发服务_中国疫情图片最新_外贸网络营销平台_天津seo排名

宁波网站开发服务_中国疫情图片最新_外贸网络营销平台_天津seo排名

2025/3/1 16:50:49 来源:https://blog.csdn.net/Vitalia/article/details/145873652  浏览:    关键词:宁波网站开发服务_中国疫情图片最新_外贸网络营销平台_天津seo排名
宁波网站开发服务_中国疫情图片最新_外贸网络营销平台_天津seo排名

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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com