3173. Bitwise OR of Adjacent Elements π
Description
Given an array nums
of length n
, return an array answer
of length n - 1
such that answer[i] = nums[i] | nums[i + 1]
where |
is the bitwise OR
operation.
Example 1:
Input: nums = [1,3,7,15]
Output: [3,7,15]
Example 2:
Input: nums = [8,4,2]
Output: [12,6]
Example 3:
Input: nums = [5,4,9,11]
Output: [5,13,11]
Constraints:
2 <= nums.length <= 100
0 <= nums[i] <= 100
Solutions
Solution 1: Iteration
We iterate through the first $n - 1$ elements of the array. For each element, we calculate the bitwise OR value of it and its next element, and store the result in the answer array.
The time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer array, the space complexity is $O(1)$.
1 2 3 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 |
|
1 2 3 |
|