Sum vs XOR – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Solutions of Algorithms Data Structures Hard HackerRank:
Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
1 Month Preparation Kit Solutions – HackerRank
C++ Sum vs XOR HackerRank Solution
#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));
}
Java Sum vs XOR HackerRank Solution
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);
}
}
Python 3 Sum vs XOR HackerRank Solution
#!/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)
JavaScript Sum vs XOR HackerRank Solution
C Sum vs XOR HackerRank Solution
#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;
}
Leave a comment below