Single Number

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

 
public class Solution {
    /*
     * Use bit manipulation. Summary: 
     * ~ - The unary complement
     * & - Bitwise and
     * ^ - Bitwise exclusive or
     * | - Bitwise inclusive or
     */
     
    public int singleNumber(int[] nums) {
        int x = 0;
        for (int num:nums) {
            //XOR ^ will return 0 when two numbers are the same.  
            x = x^num;
        }
        return x; 
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s