Sort by

recency

|

165 Discussions

|

  • + 0 comments

    Haskell

    module Main where
    
    import Data.Bits (Bits (shiftR, testBit))
    
    solve :: Integer -> Integer
    solve x = go x 0 0
      where
        go 0 idx acc = acc
        go n idx acc =
            if testBit n 0
                then go (shiftR n 1) (idx + 1) acc
                else go (shiftR n 1) (idx + 1) (acc + 2 ^ idx)
    
    main :: IO ()
    main = getLine >> getContents >>= mapM_ (print . solve . read) . lines
    
  • + 0 comments

    For x > 0, you can just subtract input from an equal number of "on" bits, e.g.

    if x = 1010 perform: 1111 - 1010 and that's the answer.

    I haven't found a really easy way (in C++) of making that 1111 number, though.

  • + 0 comments

    If you use the easy to code approach where you check every number, you can get the correct answer for small numbers. If you understand bits you'll be able to see that the correct answer is the invert of the original number. EX: 10 (0000 1010) - Answer: 5 (0000 0101) So what you can do is invert the bits until you reach the leftmost bit value on the original. C#:

    public static long theGreatXor(long x)
        {
            long result = 0;
            int i = 0;
            while(x > 1)
            {
                if((x & 1) == 0)
                {
                    result ^= (long)1 << i;
                }
                x >>= 1;
                i++;
            }
            
            return result;
        }
    
  • + 0 comments

    def theGreatXor(x): list_val_bin = list(bin(x)) y = (2**(len(list_val_bin)-2))-1 return int(bin(x ^ y), 2)

  • + 0 comments
    def theGreatXor(x):
        return sum([1 << i if b == '0' else 0 for i, b in enumerate(bin(x)[:1:-1])])