算法(二进制数中1的个数)

来源:互联网 发布:linux启动进入grub 编辑:程序博客网 时间:2024/06/05 15:07


编程之美中,1的个数的几种求法,今天先更新一种我最喜欢的方法。也是感觉很美的算法。


方法一:

package com.robin.other;public class OneNum {public static int oneNum(int data){int count = 0;while(data != 0){data &= (data-1);count++;}return count;}public static void main(String[] args) {int data = 9;int num = oneNum(data);System.out.println("the number of the one in the data is:" + num);}}


0 0
原创粉丝点击