# Java O(n) Solution with O(1) Space

• ``````public class MissingNumber {
public int missingNumber(int[] nums) {
int n = nums.length;
int sum = n * (n + 1) / 2;
for(int num : nums){
sum -= num;
}
return sum;
}
}
``````

• your solve so cool ,boys

• This post is deleted!

• @markfly Thank you. But there is a problem that the `sum` may be larger than the max integer. So the other one's `xor` solution is better.

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

• @qin3956 ok,can you explain that the row code of in for-loop what doing

• @markfly `a ^ a = 0`, so `a ^ a ^ b = b`. Assume this case:
`nums` 0 1 2 4 5
`i` 0 1 2 3 4
We miss `3`.
After the loop, `xor = 0 ^ 0 ^ 0 ^ 1 ^ 1 ^ 2 ^ 2 ^ 3 ^ 4 ^ 4 ^ 5`.
Finally `xor = 3 ^ 5`. We want to return `xor ^ i` and at that time `i` has become `4 + 1 = 5` after the for-loop. So we actually return `xor = 3 ^ 5 ^ 5 = 3` which is what we want. That make sense?

• @JackQin so thanks for you reply,many of the clear,i want study with you ,can i get your twitter?where country from?

• @markfly I am glad I have made it clear. I am just a beginner too. Sorry, I don't have twitter. We can discuss in Leetcode. :)

• @JackQin ok,I follow you Leetcode account,so I can view your dynamic

• @markfly Yeah. Come on! :)

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.