码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Single Number II

时间:2014-12-17 22:45:19      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   位运算   

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?


用一个数组记录每一位中1个的个数,如果不是3的倍数,则说明是那个single one

public class Solution {
    public int singleNumber(int[] A) {
        int bit[] = new int[32];
        int res = 0;
        for(int i=0;i<A.length;i++){
        	for(int j=0;j<32;j++){
        		if(((A[i]>>j)&1)==1) bit[j]++;
        	}
        }
        for(int i=31;i>=0;i--){
        	int bitNum = bit[i]%3;
        	if(bitNum%3!=0){
        		res +=bitNum<<i;
        	}
        }
        return res;
    }
}


[LeetCode]Single Number II

标签:java   leetcode   位运算   

原文地址:http://blog.csdn.net/guorudi/article/details/41987529

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!