public class Algorithm {public static void main (string[] args) {Long T1 = System.currenttimemillis (), for (int i =-1000000 0; i < 10000000; i++) {countone (i);} Long t2 = System.currenttimemillis (); long P1 = T2-t1;long t3 = System.currenttimemillis (); for (int i = -10000000; I < 10000000; i++) {countOne2 (i);} long T4 = System.currenttimemillis (); long P2 = t4-t3; System.out.println (p1 + "----" + p2);} /** * Bitwise operation 1 Number of * * @param x * @return */public static int countone (int x) {x = (x & 0x55555555) + ((x >> 1) &am P 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x & 0x0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f) x = (x & 0x00ff00ff) + ((x >> 8) & 0X00FF00FF);//(1) x = (x & 0x0000ffff) + ((x >> 16) & 0x0000ffff);//(2)//x = (x * 0x01010101) >> (3) return x;} /** * 1 Number * * @param x * @return */public static int countOne2 (int x) {int cnt = 0;while (x! = 0) {x &= (x-1); cnt+ +;} return CNT;}}
Results:
The time of the bitwise operation fluctuates, and the duration of the non-bitwise operation is basically around 250-270. Bit arithmetic is fast indeed.
where (1) and (2) the effect is the same as (3)
Number of 1 in binary and time comparison