[LeetCode] Bitwise OR of All Subsequence Sums

2505. Bitwise OR of All Subsequence Sums

Given an integer array nums, return the value of the bitwise OR of the sum of all possible subsequences in the array.

A subsequence is a sequence that can be derived from another sequence by removing zero or more elements without changing the order of the remaining elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
long long subsequenceSumOr(vector<int>& nums) {
long long bit[64] = {};
for(auto n : nums) {
for(long long b = 0; b < 32; b++) {
if(n & (1ll<<b)) bit[b] += 1;
}
}
long long res = 0;
for(int i = 0; i < 64; i++) {
if(i) bit[i] += bit[i-1] / 2;
if(bit[i]) res |= (1ll<<i);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/21/PS/LeetCode/bitwise-or-of-all-subsequence-sums/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.