Header Ad

HackerRank Sum vs XOR problem solution

In this HackerRank Sum vs XOR problem solution, we have given an integer N and we need to find each X such that:

0 <= X <= N

N + X = N XOR X

and then return the number of x that satisfying the criteria.

HackerRank Sum vs XOR problem solution


Problem solution in Python.

#!/bin/python3

import sys

def bitLen(int_type):
    length = 0
    while (int_type):
        int_type >>= 1
        length += 1
    return(length)

n = int(input().strip())
st = '{0:b}'.format(n)
elev = 0
#print(st)
for v in st:
    if(v == '0'):
        elev += 1
if(n == 0):
    elev -= 1
print(1<<elev)
        


Problem solution in Java.

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();
        
        if (n == 0) {
            System.out.println(1);
            return;
        }
        
        int MSB = 0;
        for (int i = 63; i >= 0; i--)
            if ( ((1L << i) & n) != 0) {
                MSB = i + 1;
                break;
            }
        long mask = 1;
        for (int i = 1; i < MSB; i++)
            mask |= mask << 1;
        long NOTn = -n - 1L;
        NOTn &= mask;
        int numBits = Long.bitCount(NOTn);
        
        long count = 1L << numBits;
                
        
        System.out.println(count);
    }
}


Problem solution in C++.

#include <bits/stdc++.h>
using namespace std;

int const N = 100 * 1000 + 16;

int main() {
  long long n;
  scanf("%lld", &n);
  auto ones = __builtin_popcountll(n);
  auto leading = __builtin_clzll(n);
  auto sz = sizeof(n)*8LL;
  auto ans = (sz-leading-ones);
  if(n==0)
    puts("1");
  else
    printf("%lld\n", (ans==0)?0:(1LL<<ans));
}


Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    long n,sum1,sum2,count=0; 
    scanf("%ld",&n);
    while(n)
        {
        sum1+=n%2?0:1;
        n/=2;
    }
    count=pow(2,sum1);
    printf("%ld",count);
    return 0;
}


Post a Comment

0 Comments