Shortest path length between two given nodes such that adjacent nodes are at bit difference 2 | Function to count set bits in a number ; Stores count of set bits in xo ; Iterate over each bits of xo ; If current bit of xo is 1 ; Update count ; Update xo ; Function to find length of shortest path between the nodes a and b ; Stores XOR of a and b ; Stores the count of set bits in xorVal ; If cnt is an even number ; Given N ; Given a and b ; Function call
function countbitdiff ( xo ) { let count = 0 ; while ( xo ) { if ( xo % 2 == 1 ) { count ++ ; } xo = Math . floor ( xo / 2 ) ; } return count ; } function shortestPath ( n , a , b ) { let xorVal = a ^ b ; let cnt = countbitdiff ( xorVal ) ; if ( cnt % 2 == 0 ) document . write ( cnt / 2 + " " ) ; else document . write ( " " + " " ) ; } let n = 15 ; let a = 15 , b = 3 ; shortestPath ( n , a , b ) ;