Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- // approach: sum of n-natural numbers
- public int missingNumber(int[] nums) {
- int n = nums.length;
- int sum1 = (n*(n+1))/2;
- int sum2 = 0;
- for(int ele : nums)
- sum2 += ele;
- return sum1 - sum2;
- }
- // approach: XOR (a^a = 0)
- public int missingNumber(int[] nums) {
- int n = nums.length;
- int xor1 = 0;
- for(int i=1; i<=n; i++)
- {
- xor1 = xor1 ^ i;
- }
- int xor2 = 0;
- for(int ele : nums)
- {
- xor2 = xor2 ^ ele;
- }
- return xor1 ^ xor2;
- }
- }
RAW Paste Data
Copied
