(Array,位操作)137. Single Number II

时间:2023-03-08 16:56:52
(Array,位操作)137. Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

public class Solution {
public int singleNumber(int[] nums) {
int res = 0;
int sum = 0;
for (int i = 0; i < 32; i++) {
sum = 0;
for (int j = 0; j < nums.length; j++) {
sum += ((nums[j] >> i) & 1); //array的题,几种思路:二分,从后往前处理,位操作。
}
res |= ((sum % 3) << i);
}
return res;
}
}