365. Count 1 in Binary【LintCode java】
2024-08-27 14:08:47
Description
Count how many 1
in binary representation of a 32-bit integer.
Example
Given 32
, return 1
Given 5
, return 2
Given 1023
, return 9
Challenge
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
解题:很简单,但是要考虑范围的问题。代码如下:
public class Solution {
/*
* @param num: An integer
* @return: An integer
*/
public int countOnes(int num) {
// write your code here
int count = 0;
long temp = (long)num;
if(temp < 0){
temp = (long)Math.pow(2,32) + temp;
}
while(temp != 0){
if(temp %2 == 1)
count++;
temp = temp / 2;
}
return count;
}
};
最新文章
- 清除打印机队列中无法清除的任务 &; 清空打印池
- makefile学习小结
- VC++ 限制窗口的大小范围的方法
- Linux 下编译安装软件,找不到共享库 xx.so 的解决办法
- BZOJ 3155: Preprefix sum
- Andorid-Fragment生命周期
- 真机測试时的错误:No matching provisioning profiles found
- python 内存泄露的诊断 - 独立思考 - ITeye技术网站
- python中openpyxl的用法【安装,以及一些基本的操作】
- cdh版本的hive安装以及配置
- day04 流程控制
- k8s运行容器之Job(四)--技术流ken
- 执行一个内容为SQL语句的字符串
- win7 Host文件修改后无效的解决办法
- 在 Linux 中自动配置 IPv6 地址
- 随机森林RandomForest
- python:turtle绘图模块
- vue/cli 3.0 脚手架【进阶】 使用 amfe-flexible 和 postcss-px2rem进行移动端适
- 浅谈 [Ljava.lang.Object 异常
- Spring @Conditional简单使用 以及 使用时注意事项一点