---
title: "Missing Number"
author: "KickCode"
date: "2016-02-25T03:46:30Z"
tags: []
categories: ["编程语言"]
slug: "missing-number"
draft: false
lastmod: "2016-02-25T03:46:30Z"
id: 2278702
url: "https://kickcode.iteye.com/blog/2278702"
---

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 =  return 2.

通过位运算，将数组里面的元素与对应的下标进行异或运算，得到一个结果result, 然后将result与数组的长度进行异或运算，得到的结果就是缺少的数字。代码如下：

```java

public class Solution {
    public int missingNumber(int[] nums) {
        if(nums == null) return -1;
        int result = 0;
        for(int i = 0; i < nums.length; i++) {
            result ^= i ^ nums[i];
        }
        return result ^ nums.length;
    }
}

```