My java XOR solution


  • 0
    X
    public class Solution {
        public int missingNumber(int[] nums) {
            if(nums == null){
                return 0;
            }
            
            int length = nums.length;
            int[] nums2 = new int[length+1];
            for(int i=0; i<length+1; i++){
                nums2[i] = i;
            }
            
            int result = 0;
            for(int i=0; i <length; i++){
                result = result^(nums[i]^nums2[i]);
            }
            result = result^nums2[length];
            return result;
            
            
        }
    }

  • 0
    D

    Your general idea is right by using XOR, but it is not necessary to create a extra array

    public int missingNumber1(int[] nums) {
        
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        int result = 0;
        
        for(int i = 0; i < nums.length; i++) {
            result ^= nums[i];
            result ^= i;
        }
        
        return result ^ nums.length;
    }
    

Log in to reply
 

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