Sum vs XOR

Sort by

recency

|

57 Discussions

|

  • + 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)
    }
    
  • + 0 comments
    def sumXor(n):
        # So basically, criteria is met when all bits are flipped to 1's for an n xor x 
        #and none are flipped to zeros
        #Meaning any non-1 in n is an option for x values, fortunately x is never greater than n making
        #this a lot easier
        if n==0:return 1
        return 2**sum([True if i=='0' else False for i in format(n,'0b')])
    
  • + 0 comments
    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            long n = in.nextLong();
            long count = 0;
            while(n != 0){
                count += (n%2 == 0)?1:0;
                n/=2; 
            }
            count = (long) Math.pow(2,count);
            System.out.println(count);
        }
    }