In this Sum vs XOR HackerRank solution, Given an integer , find each such that:
where denotes the bitwise XOR operator. Return the number of ‘s satisfying the criteria.
Example
There are four values that meet the criteria:
Return .
Function Description
Complete the sumXor function in the editor below.
sumXor has the following parameter(s):
– int n: an integer
Returns
– int: the number of values found
Input Format
A single integer, .
Constraints
Subtasks
- for of the maximum score.
Output Format
Sample Input 0
5
Sample Output 0
2
Explanation 0
For , the values and satisfy the conditions:
Sample Input 1
10
Sample Output 1
4
Explanation 1
For , the values , , , and satisfy the conditions:
Sum vs XOR HackerRank solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in C++
long sumXor(long n) {
long zerosCount = 0;
while (n > 0) {
if ((n & 1) == 0) {
zerosCount++;
}
n >>= 1;
}
return pow(2, zerosCount);
}
Problem Solution in Python
def sumXor(n):
# Write your code here
count=0
while n>0:
if n%2==0:
count=count+1
n=n//2
count = 2**count
return count
Problem Solution in Java
public static long sumXor(long n) {
// Write your code here
long number=1;
while(n!=0){
if(n%2==0) number*=2;
n/=2;
}
return number;
}
Problem Solution in JavaScript
function sumXor(n) {
if(n === 0) return 1;
let zeroCount = 0;
let binary = n.toString(2);
for(let i = 0; i < binary.length; i++){
if(binary.charAt(i) === '0') {
zeroCount++;
}
}
return Math.pow(2,zeroCount);
}
Leave a Reply