Skip to content

Instantly share code, notes, and snippets.

@alonWang
Created January 5, 2021 09:24
Show Gist options
  • Save alonWang/af917217376d414685b547a4d18fbde2 to your computer and use it in GitHub Desktop.
Save alonWang/af917217376d414685b547a4d18fbde2 to your computer and use it in GitHub Desktop.
数字的二进制标识中,左侧有多少个0. JDK实现
public static int numberOfLeadingZeros(int i) {
// HD, Count leading 0's
if (i <= 0)
return i == 0 ? 32 : 0;
int n = 31;
if (i >= 1 << 16) { n -= 16; i >>>= 16; }
if (i >= 1 << 8) { n -= 8; i >>>= 8; }
if (i >= 1 << 4) { n -= 4; i >>>= 4; }
if (i >= 1 << 2) { n -= 2; i >>>= 2; }
return n - (i >>> 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment