博客
关于我
第28题:求整数的二进制表示中1的个数
阅读量:529 次
发布时间:2019-03-08

本文共 802 字,大约阅读时间需要 2 分钟。

github:

第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

转载地址:http://hbciz.baihongyu.com/

你可能感兴趣的文章
Mysql:SQL性能分析
查看>>
mysql:SQL按时间查询方法总结
查看>>
MySQL:什么样的字段适合加索引?什么样的字段不适合加索引
查看>>
MySQL:判断逗号分隔的字符串中是否包含某个字符串
查看>>
MySQL:某个ip连接mysql失败次数过多,导致ip锁定
查看>>
MySQL:索引失效场景总结
查看>>
Mysql:避免重复的插入数据方法汇总
查看>>
MyS中的IF
查看>>
M_Map工具箱简介及地理图形绘制
查看>>
m_Orchestrate learning system---二十二、html代码如何变的容易
查看>>
M×N 形状 numpy.ndarray 的滑动窗口
查看>>
m个苹果放入n个盘子问题
查看>>
n = 3 , while n , continue
查看>>
n 叉树后序遍历转换为链表问题的深入探讨
查看>>
N!
查看>>
N-Gram的基本原理
查看>>
n1 c语言程序,全国青少年软件编程等级考试C语言经典程序题10道七
查看>>
Nacos Client常用配置
查看>>
nacos config
查看>>
Nacos Config--服务配置
查看>>