Here you can find the source of getNextLexicographicalPermutation(BigInteger v)
Parameter | Description |
---|---|
v | Source number |
public static BigInteger getNextLexicographicalPermutation(BigInteger v)
//package com.java2s; //License from project: Open Source License import java.math.BigInteger; public class Main { /**/* ww w .j av a 2 s. c o m*/ * It computes lexicographically the next permutation of the bits in the given number. * * For example 3 = 0b000011<br> * - next: 0b000101 (5)<br> * - next: 0b000110 (6)<br> * - next: 0b001001 (9)<br> * - next: 0b001010 (10)<br> * - next: 0b001100 (12)<br> * - next: 0b010001 (17)<br> * * Copied from <a href="http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation">Bit Twiddling Hacks: Compute the lexicographically next bit permutation</a> * @param v Source number * @return Bit-twiddled number */ public static long getNextLexicographicalPermutation(long v) { long t = (v | (v - 1)) + 1; return t | ((((t & -t) / (v & -v)) >> 1) - 1); } /** * It computes lexicographically the next permutation of the bits in the given number. * * For example 3 = 0b000011<br> * - next: 0b000101 (5)<br> * - next: 0b000110 (6)<br> * - next: 0b001001 (9)<br> * - next: 0b001010 (10)<br> * - next: 0b001100 (12)<br> * - next: 0b010001 (17)<br> * * Copied from <a href="http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation">Bit Twiddling Hacks: Compute the lexicographically next bit permutation</a> * @param v Source number * @return Bit-twiddled number */ public static BigInteger getNextLexicographicalPermutation(BigInteger v) { BigInteger t = v.or(v.subtract(BigInteger.ONE)).add(BigInteger.ONE); return t.and(t.negate()).divide(v.and(v.negate())).shiftRight(1) .subtract(BigInteger.ONE).or(t); } }