您的位置:首页 > 其它

第28题:求整数的二进制表示中1的个数

2015-07-02 09:25 459 查看
github:https://github.com/frank-cq/MyTest

第28题:输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,由于其二进制表示为1010,有两个1,因此输出2。

代码

package test028;

/**
* Created by cq on 2015/6/28.
* 第28题:输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,
*        由于其二进制表示为1010,有两个1,因此输出2。
*/
public class Test028 {
public static int getNumOfOne(int n){
if (n < 1){
return -1;
}

int count = 0;
while (n != 0){
if ((n&1) == 1){
count++;
}
n >>= 1;
}
return count;
}

public static void main(String[] args){
System.out.println("11的二进制表示中有 "+getNumOfOne(11)+" 个1。");
}
}


执行结果

Connected to the target VM, address: '127.0.0.1:3174', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:3174', transport: 'socket'
11的二进制表示中有 3 个1。

Process finished with exit code 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: