cKK

............当你觉得自己很辛苦,说明你正在走上坡路.............坚持做自己懒得做但是正确的事情,你就能得到别人想得到却得不到的东西............

导航

(Array,位操作)137. Single Number II

Posted on 2016-04-19 14:00  cKK  阅读(158)  评论(0编辑  收藏  举报

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 Solution {
    public int singleNumber(int[] nums) {
      int res = 0;
		int sum = 0;
		for (int i = 0; i < 32; i++) {
			sum = 0;
			for (int j = 0; j < nums.length; j++) {
				sum += ((nums[j] >> i) & 1);      //array的题,几种思路:二分,从后往前处理,位操作。
			}
			res |= ((sum % 3) << i);
		}
		return res;
    }
}