XOR and SUM Java


  • 0
    I
    /* Sum of N + 1 formula */
    public int missingNumber(int[] nums) {
        int sum = ((nums.length + 2) * (nums.length + 1)) / 2;
        for(int a : nums) {
            sum -= (a + 1);
        }
        
        return sum - 1;
    }
    
    /* XOR */
    public int missingNumber(int[] nums) {
            int xor = 0;
            for(int i = 0; i < nums.length + 1; i++) {
                xor ^= i;
            }
            
            for(int num : nums) {
                xor ^= num;
            }
            
            return xor;
    }
    

Log in to reply
 

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