News Leaflets
0 94

Given an array A[] of length N, the task is to count the number of elements of the array having their MSB and LSB set.

Examples:

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

Naive approach: The basic idea to solve the problem is to convert all the array element into their binary form and then check if first and last bit of the respective integers are set or not.

Time complexity: O(N * d), where d is the bit count in the maximum element of the array.
Auxiliary Space: O(1)

Efficient Approach: The idea to solve the problem is by traversing the array and counting the number of odd elements present in the array, because all the odd integers have LSB and MSB set.

Follow the steps mentioned below to solve the problem:

• Traverse the array A[] of length and for each element:
• Check, if the element is odd or not.
• If Yes, increase the count by 1
• Return the count.

Below is the implementation of the above approach:

## C++

 ` `  `#include ` `using` `namespace` `std;` ` `  `int` `count(vector<``int``> arr, ``int` `n)` `{` `    ``int` `i, count = 0;` `    ``for` `(i = 0; i < n; i++) {` ` `  `        ` `        ` `        ``if` `(arr[i] % 2)` `            ``count++;` `    ``}` `    ``return` `count;` `}` ` `  `int` `main()` `{` `    ``int` `N = 5;` `    ``vector<``int``> arr = { 1, 2, 3, 7, 8 };` ` `  `    ``cout << count(arr, N);` `    ``return` `0;` `}`

Time Complexity: O(N)
Auxiliary Space: O(1).