题目
类型:位运算
解题思路
可以用位运算
但是我选择用数学
思路:将从 0 到 n 的全部整数之和记为 total,根据高斯求和公式算出和
将数组的元素之和记为 arrSum,则 arrSum 比 total 少了丢失的一个数字,因此丢失的数字即为 total 与 arrSum 之差。
代码
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int total = n * (n + 1) / 2;
int arrSum = 0;
for (int i = 0; i < n; i++) {
arrSum += nums[i];
}
return total - arrSum;
}
}