码迷,mamicode.com
首页 > 其他好文 > 详细

二进制中1的个数以及时间比较

时间:2015-03-18 21:47:35      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:二进制   1的个数   位运算   时间比较   

public class Algorithm {

	public static void main(String[] args) {
		long t1 = System.currentTimeMillis();
		for (int i = -10000000; 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);
	}

	/**
	 * 位运算求1的个数
	 * 
	 * @param x
	 * @return
	 */
	public static int countOne(int x) {
		x = (x & 0x55555555) + ((x >> 1) & 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) >> 24;(3)
		return x;
	}

	/**
	 * 1的个数
	 * 
	 * @param x
	 * @return
	 */
	public static int countOne2(int x) {
		int cnt = 0;
		while (x != 0) {
			x &= (x - 1);
			cnt++;
		}
		return cnt;
	}
}

结果:

技术分享



技术分享

位运算的时间有波动,非位运算的耗时基本上在250-270左右。位运算的速度确实快。

其中(1)和(2)的效果与(3)相同

二进制中1的个数以及时间比较

标签:二进制   1的个数   位运算   时间比较   

原文地址:http://blog.csdn.net/u010786672/article/details/44423003

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!