Sum vs XOR

Sort by

recency

|

59 Discussions

|

  • + 0 comments

    Python 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

    def sum_xor(n):
        # Time complexity: O(log(n))
        # Space complexity (ignoring input): O(1)
        if n == 0:
            return 1
        # count 0 in binary of number
        count = 0
        while n > 0:
            if n & 1 == 0:
                count += 1
            n = n >> 1
    
        return 2**count
    
  • + 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
    }
    
  • + 0 comments

    My Solution in java8:

    public static long sumXor(long n) {
    // Write your code here
    Long res = 0L, nn = n;
    res = (long)Math.pow(2,(Long.toBinaryString(nn).chars().filter(x -> x == '0').count()));
    return n == 0 ? 1 : res;
    }
    
  • + 0 comments

    I understand 2 ** (number of zero) because each 0 has two posibilities- either 0 or 1. But, can someone help understand why it covers the case

    num ^ 0 = num + 0?

    Thanks a lot

  • + 0 comments

    Rust:

    fn sumXor(n: i64) -> i64 {
        let zeros = n.count_zeros() - n.leading_zeros();
        2_i64.pow(zeros)
    }