剑指 Offer 56 – II. 数组中数字出现的次数 II(Sword finger offer 56 – II Number of occurrences of numbers in the array II)

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int singleNumber(int[] nums) {
        int ans = 0;
        for (int i = 0; i < 31; ++i) {
            int sum = 0;
            for (int num : nums) {
                sum += (num >> i & 1);
            }
            ans |= (sum % 3) << i;
        }
        return ans;
    }
}
————————

In an array nums, except that one number appears only once, all other numbers appear three times. Please find the number that appears only once.

Source: leetcode
Link: https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

class Solution {
    public int singleNumber(int[] nums) {
        int ans = 0;
        for (int i = 0; i < 31; ++i) {
            int sum = 0;
            for (int num : nums) {
                sum += (num >> i & 1);
            }
            ans |= (sum % 3) << i;
        }
        return ans;
    }
}