`
devon.k
  • 浏览: 90598 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Count 1 amount in a binary number, So GraceFul

阅读更多
给你一个10进制的数将其变成2进制后会有多少个1 ?
	/*
	 * i.e  很优雅(GraceFul)
	 * binary(hex) b = 10101100 
	 *         b - 1 = 10101011 
	 *         					c = 1 
	 * b=(b&(b - 1)) = 10101000
	 *         b - 1 = 10100111
	 *         					c = 2
	 * b=(b&(b - 1)) = 10100000
	 *         b - 1 = 10011111 			
	 *         					c = 3
	 * b=(b&(b - 1)) = 10000000
	 *         b - 1 = 01111111 			
	 *         					c = 4
	 *    	      b = 00000000
	 *    						break
	 */
	public int countOneGraceful(int hex) {
		int c = 0;
		for (; hex != 0; c ++)
			hex &= hex - 1;
		
		return c;
	}

         /*
          * 用于与优雅对比的函数
            */
	public int countOne(int hex) {
		int c = 0;
		for(; (hex/2) != 0; hex/=2)
			if ((hex%2) == 1)
				c ++;
		
		if ((hex%2) == 1)
			c ++;
		
		return c;
	}

         /*
          * 测试
          */
	public static void main(String[] args) {
		Fibonacci f = new Fibonacci(); //我的类
		
		System.out.println("127 to binary: " + Integer.toBinaryString(127));
		System.out.println(f.countOneGraceful(127));
		
		System.out.println("128 to binary: " + Integer.toBinaryString(128));
		System.out.println(f.countOneGraceful(128));
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics