Question
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?
https://oj.leetcode.com/problems/single-number-ii/
*Difficulty: Hard, Frequency: Medium
Solution
public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
int[] cnt = new int[32];
Arrays.fill(cnt, 0);
for(int i= 0; i < 32; i++){
for(int j = 0; j < nums.length; j++){
if(((nums[j] >> i) & 1) != 0){
cnt[i]++; //check how many 1s in ith bit
}
}
result = result | ( (cnt[i]%3) << i ); //get target num's ith bit (others even if have 1, since appear 3 times will be 0 after mod 3)
}
return result;
}
}
bit operations:
https://en.wikipedia.org/wiki/Bitwise_operation