给定数组中设置了 MSB 和 LSB 的整数计数
给定一个长度为N的数组A[] ,任务是计算数组中设置了 MSB 和 LSB 的元素的数量。
例子:
Input: A[] = {2, 3, 1, 5}
Output: 3
Explanation: Binary representation of the array elements {2, 3, 1, 5} are {10, 11, 1, 101}
The integers 3, 1, 5 are the integers whose first and last bit are set bit.
Input: A[] = {2, 6, 18, 4}
Output: 0
幼稚方法:解决问题的基本思路是将所有数组元素转换为二进制形式,然后检查相应整数的第一位和最后一位是否已设置。
时间复杂度: O(N * d),其中d是数组最大元素中的位数。
辅助空间: O(1)
有效方法:解决问题的想法是通过遍历数组并计算数组中存在的奇数元素的数量,因为所有奇数都设置了 LSB 和 MSB。
请按照以下步骤解决问题:
- 遍历数组A[]的长度和每个元素:
- 检查元素是否为奇数。
- 如果是,则将计数增加 1
- 返回计数。
下面是上述方法的实现:
C++
// C++ code for the above approach:
#include
using namespace std;
// Count the number of odd elements
int count(vector arr, int n)
{
int i, count = 0;
for (i = 0; i < n; i++) {
// If element is odd
// increment count
if (arr[i] % 2)
count++;
}
return count;
}
// Driver Code
int main()
{
int N = 5;
vector arr = { 1, 2, 3, 7, 8 };
cout << count(arr, N);
return 0;
}
Java
// Java code for the above approach:
import java.io.*;
class GFG {
// Count the number of odd elements
static int count(int[] arr, int n)
{
int i, count = 0;
for (i = 0; i < n; i++) {
// If element is odd
// increment count
if (arr[i] % 2 == 1)
count++;
}
return count;
}
// Driver Code
public static void main (String[] args) {
int N = 5;
int arr[] = { 1, 2, 3, 7, 8 };
System.out.println(count(arr, N));
}
}
// This code is contributed by hrithikgarg03188.
Python3
# Python3 code for the above approach
# count the number of odd elements
def count(arr, n):
i = 0
count = 0
for i in range(n):
if arr[i] % 2:
count += 1
return count
# Driver Code
N = 5
arr = [1, 2, 3, 7, 8]
print(count(arr, N))
# This code is contributed by phasing17
C#
// C# code for the above approach:
using System;
class GFG {
// Count the number of odd elements
static int count(int[] arr, int n)
{
int i, count = 0;
for (i = 0; i < n; i++) {
// If element is odd
// increment count
if (arr[i] % 2 == 1)
count++;
}
return count;
}
// Driver Code
public static void Main()
{
int N = 5;
int[] arr = { 1, 2, 3, 7, 8 };
Console.Write(count(arr, N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
3
时间复杂度: O(N)
辅助空间: O(1)。