[Offer] [56-2] [array number unique only appear once]

Title Description

  In addition to an array of a number appears only once, other figures have appeared three times . Find the number that appears only once

[Cow brush off questions address network] No

Ideas analysis

  If a number appears three times, then there three times its binary representation of each bit (0 or 1). Each bit of each binary digits add up if all three appear representation, then each and can be divisible by 3. Each one adds up all the numbers we have an array of binary representation. If a bit and divisible by 3, then the number that appears only once in the corresponding binary representation of the one who is 0; otherwise, it is 1.

Test Case

  1. Function Testing: The only appears only once figures were 0, positive, negative; digital repeated three times respectively 0, positive, negative.

Java code

public class Offer056_02 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

    public static int findNumberAppearingOnce(int[] array) {
        return Solution1(array);
    }


    private static int Solution1(int[] array) {
        if(array==null || array.length<=0) {
            return -1;
        }
        
        int[] bitSum = new int[32];
        for(int i=0;i<array.length;i++) {
            int bitMask = 1;
            for(int j=31;j>=0;j--) {//将每个数字的每一位存储到bitSum中,并且对应的位相加
                int bit = array[i] & bitMask;
                if(bit!=0) {
                    bitSum[j]+=1;
                }
                bitMask = bitMask<<1;
            }
        }
        
        int result =0;
        for(int i=0;i<32;i++) {
            result = result<<1;
            result += bitSum[i]%3;
        }
        
        return result;
    }

    private static void test1() {
        int[] array = {1,1,1,4,5,4,4,2,2,2};
        System.out.println(findNumberAppearingOnce(array)); 
    }

    private static void test2() {

    }
    private static void test3() {

    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer562-shu-zu-zhong-wei-yi-zhi-chu-xian-yi-ci-de.html