Skip to content

Instantly share code, notes, and snippets.

@a6y3ap
Created January 6, 2019 22:20
Show Gist options
  • Save a6y3ap/3c145857dc1fe9c548e2d55a0ab72787 to your computer and use it in GitHub Desktop.
Save a6y3ap/3c145857dc1fe9c548e2d55a0ab72787 to your computer and use it in GitHub Desktop.
Joshphus Problem using Bitwise Operation (Java)
/*
* Solution of Joshphus Problem using Bitwise Operation
* Wikipedia: https://en.wikipedia.org/wiki/Josephus_problem
* YouTube: https://www.youtube.com/watch?v=uCsD3ZGzMgE
*
* ====================== EXPLANATION ======================
*
* n (41) the number of people standing in the circle
* n = 101001
*
* Left Shift n
* (n<<1) = 1010010
*
* Flip the last bit
* ((n<<1) | 1) = 1010011
*
* To Flip the First Set Bit
* n = 101001
*
* n*2
* Multiply n by 2
* 41 x 2 = 82
* 82 = 1010010
*
* Integer.highestOneBit(n*2)
* Get highest set bit position
* 64 = 1000000
*
* ~Integer.highestOneBit(n*2)
* Taking compliment
* ~64 = 0111111
*
* ~Integer.highestOneBit(n*2) & ((n<<1) | 1)
* Bitwise And to copy bits exists in both operands.
* 1010011
* & 0111111
* -----------
* 0010011
* -----------
*/
public static int getSafePosition(int n) {
// int n1 = ~Integer.highestOneBit(n*2);
// int n2 = ((n<<1) | 1);
// return n1 & n2;
return ~Integer.highestOneBit(n*2) & ((n<<1) | 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment