Sunday, November 24, 2013

LeetCode Problem : Single Number II

Problem



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?

Code

int singleNumber(int A[], int n) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int result = 0;
    int int_size = sizeof(int)*CHAR_BIT;
    for(int j = 0; j < int_size;++j){
        int sum = 0;
        int x = 1 << j;
        for(int i = 0; i < n;++i){
            if(A[i] & x)
             ++sum;
        }
        if(sum % 3 != 0)
            result |= x;
    }
    return result;
}

No comments:

Post a Comment