3702. Longest Subsequence With Non-Zero Bitwise XOR
</> Solution
/**
* Problem: LeetCode 3702 - Longest Subsequence With Non-Zero Bitwise XOR
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int longestSubsequence(int[] nums) {
int totalXor = 0;
boolean hasNonZero = false;
for (int num : nums) {
totalXor ^= num;
if (num != 0) {
hasNonZero = true;
}
}
int n = nums.length;
if (totalXor != 0) {
return n;
}
return hasNonZero ? n - 1 : 0;
}
}
"""
Problem: LeetCode 3702 - Longest Subsequence With Non-Zero Bitwise XOR
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def longestSubsequence(self, nums: List[int]) -> int:
total_xor = 0
has_non_zero = False
for num in nums:
total_xor ^= num
if num != 0:
has_non_zero = True
n = len(nums)
if total_xor != 0:
return n
return n - 1 if has_non_zero else 0
/**
* Problem: LeetCode 3702 - Longest Subsequence With Non-Zero Bitwise XOR
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
/**
* Problem: LeetCode 3702 - Longest Subsequence With Non-Zero Bitwise XOR
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int longestSubsequence(vector<int>& nums) {
int totalXor = 0;
bool hasNonZero = false;
for (int num : nums) {
totalXor ^= num;
if (num != 0) {
hasNonZero = true;
}
}
int n = nums.size();
if (totalXor != 0) {
return n;
}
return hasNonZero ? n - 1 : 0;
}
};
/**
* Problem: LeetCode 3702 - Longest Subsequence With Non-Zero Bitwise XOR
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var longestSubsequence = function(nums) {
let totalXor = 0;
let hasNonZero = false;
for (const num of nums) {
totalXor ^= num;
if (num !== 0) {
hasNonZero = true;
}
}
const n = nums.length;
if (totalXor !== 0) {
return n;
}
return hasNonZero ? n - 1 : 0;
};