Sum vs XOR

  • + 0 comments

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn sum_xor(n: i64) -> i64 {
        // Time complexity: O(log(n))
        // Space complexity (ignoring input): O(1)
        let mut n = n;
        let mut zeros_in_binary = 0;
        while n > 1 {
            if n & 1 == 0 {
                zeros_in_binary += 1;
            }
            n = n >> 1;
        }
    
        // The answer is that the number can have 1 or 0 in the positions where 'n' has 0, so 2 to the n
        return 1<<zeros_in_binary
    }