您的位置:首页 > 其它

Single Number II

2015-09-17 03:30 281 查看
Given an array of integers, every element appears three times
except for one. Find that single one.

public int singleNumber(int[] A) {
		if (A == null || A.length == 0)
			return 0;
		int[] a = new int[32];
		for (int i = 0; i < A.length; i++) {
			for (int j = 0; j < 32; j++) {
				//1<<j == 1向左移动j位
				//A[i] & (1 << j)可以判断A[i]二进制中有哪几位为1
				if ((A[i] & (1 << j)) != 0)
					//[j]这是倒过来的
					//e.g A[i] = 11 = 1011 ==>
					//a[j] = 11010000...
					//+1 %3后,所有出现3次的数变为0
					a[j] = (a[j] + 1) % 3;
			}
		}
		int result = 0;
		for (int i = 0; i < 32; i++) {
			if (a[i] > 0)
				//a[i] << i将反过来的结果正过来
				result |= (a[i] << i); 
		}
		return result;
	}


http://shmilyaw-hotmail-com.iteye.com/blog/2153924
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: