第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
相关文章推荐
- 处理json中的null
- 模拟售票窗口前的顾客队列,在队列最前面的人最先买到票。已经买到票的顾客出队,当库存票售完或队伍里没人则停止销售。
- 用NDK调用Android手机自带的openssl库函数
- Python Windows error code
- 关于子查询的一些小东西
- springAOP日志记录数据库项目实例
- mysql压缩表空间
- git实用命令集锦
- 【C语言】模拟实现strchr函数.即在一个字符串中查找一个字符第一次出现的位置并返回
- Spring加载applicationContext.xml应用上下文的方式
- Web服务器
- gdb 死锁线程
- JAVA的用途是什么?如果学好JAVA能干什么【转】
- 【C语言】模拟实现库函数strcat函数
- enumerateObjectsUsingBlock、enumerateObjectsWithOptions、enumerateObjectsAtIndexes、makeObjectsPerfor使用
- acdream 1222 Quantization Problem [dp]
- Factorial
- PHP 开放JSON格式接口实例
- iOS高级开发, 开机启动, 无限后台运行, 监听进程
- Log4j详细使用教程