Skip to content

Instantly share code, notes, and snippets.

@sahilkashyap64
Last active October 30, 2019 22:06
Show Gist options
  • Save sahilkashyap64/3bb4b35eb7469b463399560c7a2be871 to your computer and use it in GitHub Desktop.
Save sahilkashyap64/3bb4b35eb7469b463399560c7a2be871 to your computer and use it in GitHub Desktop.
//A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
//For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
//solution 1
function solution(N) {
// write your code in JavaScript (Node.js 8.9.4)
return Math.max(0,...(N >>> 0)
.toString(2)
.split('1')
.map(v => v.length)
.slice(1,-1) );
}
//1st solution
///N>>>0 The >>> 0 is an abuse of the operator to convert any numeric expression to an "integer" or non-numeric expression to zero.
//convert the number in binary
//divide the binary where it encounters 1 ,it is return as array
//check each elements length
//remove the first and last
//Return the maximum value Math.max to make it work you need to pass array using spread operator.
//
// Find value that occurs in odd number of elements.
//solution 2
function solution(A) {
let result = 0;
for (let element of A) {
// Apply Bitwise XOR to the current and next element
result =result^ element;
}
return result;
}
//explaination of solution 2
// 1. Loop through the elements and xor them to each other
//xor condition is that if the bits are same dissolve them if bits are different return 1 or true
//e.g A ^ B= output
// 0 xor 0 = 0
// 1 xor 0 = 1
// 0 xor 1 = 1
// 1 xor 1 = 0
//A=[1,1,2,2,3,3,4]; //my array
//1=0001 ,2=0010,3=0011,4=1000 //bit represntation of numbers
//have a empty result variable with intial value of zer0
//loop through array element
//result=result^element
//1st iteration 0 =0 ^ 0001; //now value of result is 0001 element =1
//2nd iteration 0=0001 ^ 0001 // since 1^1 =0 the result gets 0 element =1 //bits are same disolve them
//3rd iteration 0010=0 ^ 0010 // since 0^2 =0 the result gets 0 element =2
//4th iteration 0=0010 ^ 0010 // since 2^2 =0 the result gets 0 element =2 //bits are same disolve them
//5th iteration 0011=0 ^ 0011 // since 0^3 =0 the result gets 0 element =3
//6th iteration 0=0011 ^ 0011 // since 3^3 =0 the result gets 0 element =3 //bits are same disolve them
//7th iteration 1000=0000^1000 // since 0^4 =4 the result gets 0 element =4 //keep this in result as loop ended
//return the value of result i.e 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment