提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
返回在指定的起始索引上或之后出现的设置为true的第一位的索引。
//package com.nowjava; /** * 时 代 J a v a - N o w J a v a . c o m 提 供 **/ public class Main { public static void main(String[] argv) throws Exception { int bitset = 2; int fromIndex = 2; System.out.println(nextSetBit(bitset, fromIndex)); } /** maximum index of a bitset (minimum index is 0) */ public static final int MAX_INDEX = 31; /* *来 自 时代Java公众号 - nowjava.com */ /** int with all bits set */ public static final int INT_MASK = 0xffffffff; /** * Returns the index of the first bit that is set to <code>true</code> that * occurs on or after the specified starting index. If no such bit exists * then -1 is returned. * * To iterate over the <code>true</code> bits in a bitset, use the following * loop: * * <pre> * for (int i = nextSetBit(bitset, 0); i >= 0; i = nextSetBit(bitset, i + 1)) * ; // do something * </pre> * * @param bitset * a bitset. * @param fromIndex * the bit index after which the first bit that is set to * <code>true</code> is returned. * @return the index of the first bit that is set to <code>true</code> that * occurs on or after the specified starting index * @throws IndexOutOfBoundsException * if the specified index is negative */ public static int nextSetBit(int bitset, int fromIndex) throws IndexOutOfBoundsException { checkIndexRange(fromIndex, Integer.MAX_VALUE); if (fromIndex > MAX_INDEX) return -1; bitset &= (INT_MASK << fromIndex); if (bitset != 0) return Integer.numberOfTrailingZeros(bitset); return -1; } /** * Throws an {@link IndexOutOfBoundsException} if the given bit index is * negative or if it the second argument is <code>true</code> also if the * index is greater than {@link #MAX_INDEX}. * * @param index * @param checkMax * @throws IndexOutOfBoundsException */