Fork me on github

【每日一题】137. 只出现一次的数字 II

https://leetcode-cn.com/problems/single-number-ii/

思路:二进制位上的数字之和为 3 的倍数

class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;
        for(int i = 0; i < 32; i++){
            int total = 0;
            for(int num : nums){
                total += (num >> i) & 1;  // 从低位开始向上统计
            }
            if(total % 3 == 1){
                res |= (1 << i);          // res 初始为 0, 同或相当于加上
            }
        }
        return res;
    }
}
posted @ 2021-04-30 10:05  zjy4fun  阅读(36)  评论(0编辑  收藏  举报