Java [Leetcode 137]Single Number II

题目描述:

Given an array of integers, every element appears three times except for one. Find that single one.

解题思路:

具体参考Detailed explanation and generalization of the bitwise operation method for single numbers

讲的实在是很全面,而且拓展到了一般的情况,膜!!

代码如下:

public class Solution{
	public int singleNumber(int[] nums){
		int x1 = 0;
		int x2 = 0;
		int mask = 0;

		for(int i : nums){
			x2 ^= x1 & i;
			x1 ^= i;
			mask = ~(x1 & x2);
			x2 &= mask;
			x1 &= mask;
		}
		
		return x1;
	}
}

  

posted @ 2016-04-03 18:28  scottwang  阅读(305)  评论(0编辑  收藏  举报