题目来源
力扣2917找出数组中的kor值
题目概述
给你一个下标从 0 开始的整数数组 nums 和一个整数** **k 。
nums 中的 K-or
是一个满足以下条件的非负整数:
只有在 nums 中,至少存在 k 个元素的第 i 位值为 1 ,那么K-or
中的第 i 位的值才是 1 。 返回 nums 的 K-or 值。
注意 :对于整数 x ,如果(2i AND x) == 2i
,则 x 中的第 i 位值为 1 ,其中 AND 为按位与运算符。
思路分析
其实就是统计数组每个数据二进制表示第i位是否为1,如果满足大于k个数据的第i为1,kor值加 1 << i。
代码实现
java实现
public class Solution {public int findKOr(int[] nums, int k) {int kor = 0;boolean flag = true;int length = nums.length;int site = 0;while (flag) {int notZero = length;int count = 0;for (int i = 0; i < length; i++) {count += nums[i] & 1;nums[i] >>= 1;if (nums[i] == 0) {notZero--;}}if (count >= k) {kor += 1 << site;}site++;flag = notZero > 0;}return kor;}
}
c++实现
class Solution {
public:int findKOr(vector<int>& nums, int k) {int kor = 0;int length = nums.size();int notZero = length;int site = 0;while (notZero > 0) {notZero = length;int count = 0;for (int i = 0; i < length; i++) {count += nums[i] & 1;nums[i] >>= 1;if (nums[i] == 0) {notZero--;}}if (count >= k) {kor += 1 << site;}site++;}return kor;}
};