Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Method 1 (bit manipulation):

public class Solution {
    public int missingNumber(int[] nums) {
        int xor = 0, i = 0; 
        
        for ( i = 0; i <  nums.length; i++) {
            xor ^= i^nums[i];
        }
        
        return xor ^ nums.length; 
    }
}

Method 2 (without manipulation)

 
public class Solution {
    public int missingNumber(int[] nums) {
        int sum = 0; 
        int i = 0; 
        
        for (i = 0; i < nums.length; i++) {
            sum = sum + i - nums[i];
        }
        
        return sum + nums.length; 
    }
}
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