(java)leetcode Number of 1 Bits
2015-11-12 18:34
501 查看
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming
weight).
For example, the 32-bit integer ’11' has binary representation
so the function should return 3.
思路:把这个数转换成2进制数,然后统计1出现的次数就行了
代码如下(已通过leetcode)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
String str=Integer.toBinaryString(n);
//System.out.println(str);
int count=0;
for(int i=0;i<str.length();i++) {
if(str.charAt(i)=='1') count++;
}
return count;
}
}
weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
思路:把这个数转换成2进制数,然后统计1出现的次数就行了
代码如下(已通过leetcode)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
String str=Integer.toBinaryString(n);
//System.out.println(str);
int count=0;
for(int i=0;i<str.length();i++) {
if(str.charAt(i)=='1') count++;
}
return count;
}
}
相关文章推荐
- loadrunner之java协议脚本编写
- Google Java编程风格指南
- 数组和List之间的转换
- Jmeter插件——Java实现thrift客户端
- POJ 2081 JAVA
- Gson出现javaBean在打包后无效的问题
- 时间格式化的format.setLenient(false)
- filter
- Java 多线程 线程间的通信——wait及notify方法
- jenkins执行启动java程序后,会杀掉程序的解决方法
- jenkins执行启动java程序后,会杀掉程序的解决方法
- Struts2系统学习(3)Action深入
- POJ 2085 JAVA
- Java初学者不得不知的概念,JDK,JRE,JVM的区别?
- java基础知识回顾(二)
- 利用AXIS2,根据已有WSDL生成java源程序
- java web 中的WEB-INF文件夹
- spring―hibernate查询
- java中volatile关键字的含义
- Java连接FTP服务器并且实现对其文件的上传和下载