The sword refers to Offer 56 II. The number of occurrences of the number in the array (comprehensive bit operation)

Saturday, February 6, 2021, the weather is fine [Don’t lament the past, don’t waste the present, don’t fear the future]


Contents of this article


1. Introduction

Sword Finger Offer 56-II. Number of occurrences of numbers in the array II
Insert picture description here

2. Solution

If a number appears three times, then each bit (0 or 1) of its binary representation also appears three times. If you add up each bit of the binary representation of all three-occurring numbers, then the sum of each bit can be divisible by 3.

We add up each bit of the binary representation of all the numbers in the array. If the sum of a certain bit is divisible by 3, then the corresponding bit in the binary representation of the number that appears only once is 0; otherwise, it is 1.

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
        vector<int> counts(32,0);
        // 记录所有数字各二进制位的 1 出现次数之和
        for(int num : nums) {
    
    
            for(int j = 0; j < 32; j++) {
    
    
                counts[j] += num & 1;
                num >>= 1;
            }
        }
        int res = 0, m = 3;
        // 利用 左移操作 和 或运算 ,将 counts 数组中各二进位的值恢复到数字 res 上
        for(int i = 0; i < 32; i++) {
    
    
            res <<= 1;
            res |= counts[31 - i] % m;
        }
        return res;
    }
};

references

"Sword Finger Offer Second Edition"

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/solution/mian-shi-ti-56-ii-shu-zu-zhong-shu-zi-chu-xian-d-4/

Guess you like

Origin blog.csdn.net/m0_37433111/article/details/113731125