// find number of 1 bits int n = 10; //101 int count =0; // will repeatedly do and of number with(n-1), as this flips the LSB 1 bit while(n !=0) { count++; n &= (n-1); } System.out.println("count is " + count);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter