代码改变世界

137_Single Number II

2016-03-11 15:35  FTD_W  阅读(138)  评论(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?

 

给定一个数组,每个数字出现3次,只有一个数字出现一次,找出该数字

 

int型整数有32位,统计每个位上32个数字有多少个该为是1,若不是3的倍数则单独的数字该位上是1

int singleNumber(int* nums, int numsSize) {
    int result = 0;//最终结果
    for(int i = 0; i < 32; i++)
    {
        int bit = 1 << i;//1左移i个位置
        int bitCount  = 0;//在int型整数的某位上出现1的个数
        for(int j = 0; j < numsSize; j++)
        {
            if(nums[j] & bit)
            {
                bitCount++;
            }
        }
        if(bitCount % 3 != 0)
        {
            result += bit;
        }
    }
    return result;
}