Leetcode-SingleNumberII

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?

public class SingleNumberII {
	public int singleNumberII(int A[]){
		int bitInt[] = new int[32];
		//给数组初始化
		for (int i = 0; i<32; i++){
			bitInt[i] = 0;
		} 
        int result=0;  
        for(int i=0; i<32; i++){  
            for(int j=0; j<A.length; j++){  
            	bitInt[i]+=(A[j]>>i)&1;  
            }  
            result|=(bitInt[i]%3)<<i;  
        }  
        return result;  
	}
}

Junit单元测试:

public class SingleNumberIITest {
	SingleNumberII s;
	@Before
	public void setUp() throws Exception {
	}


	@After
	public void tearDown() throws Exception {
	}


	@Test
	public void testSingleNumberII() {
		s = new SingleNumberII();
//		int B[] = {43,16,45,89,45,-2147483648,45,2147483646,-2147483647,-2147483648,43,2147483647,-2147483646,-2147483648,89,-2147483646,89,-2147483646,-2147483647,2147483646,-2147483647,16,16,2147483646,43};
		int B[] = {-1,2,2,2};
		int result = s.singleNumberII(B);
//		assertEquals(2147483647, result);
		assertEquals(-1,result);
//		fail("Not yet implemented");
	}


}

说明:这种方法是一种通用的解决方法;

知识:左移、右移i位的含义(正负数相同);

          &与|跟左移、右移的结合使用;

难点:考虑到输入数据有负数的情况。

你可能感兴趣的:(java,LeetCode,Java学习笔记,II,SingleNumber)