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

LeetCode--Single Number II

时间:2015-01-15 11:03:15      阅读:157      评论:0      收藏:0      [点我收藏+]

标签: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?

class Solution 
{
public:
    int singleNumber(int A[], int n) 
    {
        if(n==0)
            return -1;
        const int num = 32;
        int bit[num];
        for(int i=0; i<num; i++)
            bit[i] = 0;
        for(int i=0;i<n;i++)
        {
            int temp = A[i];
            for(int j=num-1;j>=0;j--)
            {
                bit[j] = bit[j]+(temp&1);
                temp = temp>>1;
                bit[j] = bit[j]%3;
            }
        }
        int res = 0;
        for(int j=0; j<num; j++)
            res = res*2 + bit[j];
        return res;
    }
};


LeetCode--Single Number II

标签:leetcode   位运算   

原文地址:http://blog.csdn.net/shaya118/article/details/42737061

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