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

leetcode 刷题之路 84 Single Number II

时间:2014-08-13 15:00:06      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   2014   amp   

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

给定一个包含n个整数的数组,除了一个数出现一次外所有的整数均出现三次,找出这个只出现一次的整数。

思路,根据数组构成的特点可知,数组中所有数的某一位上1的个数总和为3*n或者3*n+1。

当只出现一次的整数该位为0时,总和为3*n,当只出现一次的整数该位为1时,总和为3*n+1。

因此我们可以计算数组中所有整数的每一位上1的个数,然后进行取模运算就可以得出只出现一次的整数每一个位的值。

AC code:

class Solution {
public:
    int singleNumber(int A[], int n) 
    {
        int res=0,numof1=0;
        for(int i=0;i<8*sizeof(int);i++)
        {
            for(int j=0;j<n;j++)
            {
                if((A[j]&1<<i)!=0)
                    numof1++;
            }
            if(numof1%3!=0)
                res|=1<<i;
            numof1=0;
        }
        return res;
    }
};


leetcode 刷题之路 84 Single Number II,布布扣,bubuko.com

leetcode 刷题之路 84 Single Number II

标签:style   blog   color   io   for   ar   2014   amp   

原文地址:http://blog.csdn.net/u013140542/article/details/38535725

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