Leetcode_191_Number of 1 Bits
2016-01-21 17:01
302 查看
本文是在学习中的总结。欢迎转载但请注明出处:/article/1372505.html
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming
weight).
For example, the 32-bit integer ’11' has binary representation
so the function should return 3.
思路:
(1)题意为给定一个无符号数。返回其相应二进制数中1的个数。
(2)该题主要考察进制的转换操作。java中没有无符号数字(为什么没有能够百度下)。无符号数即给定的数都是非负数。这样我们能够通过java自带类库中的Integer.toBinaryString(value)将指定整数专为二进制数。然后求得二进制数中包括1的个数就可以。详情见下方代码。
(3)希望本文对你有所帮助。
算法代码实现例如以下:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming
weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
思路:
(1)题意为给定一个无符号数。返回其相应二进制数中1的个数。
(2)该题主要考察进制的转换操作。java中没有无符号数字(为什么没有能够百度下)。无符号数即给定的数都是非负数。这样我们能够通过java自带类库中的Integer.toBinaryString(value)将指定整数专为二进制数。然后求得二进制数中包括1的个数就可以。详情见下方代码。
(3)希望本文对你有所帮助。
算法代码实现例如以下:
/** * @param liqq 直接用类库 */ public int hammingWeight(int value) { int count = 0; String binaryString = Integer.toBinaryString(value); for (int i = 0; i < binaryString.length(); i++) { char charAt = binaryString.charAt(i); if (charAt == '1') { count++; } } return count; }
/** * @param liqq 简化类库中toBinaryString方法的使用 */ // you need to treat n as an unsigned value public int hammingWeight(int value) { int count = 0; // String binaryString = Integer.toBinaryString(value); char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; char[] buf = new char[32]; int charPos = 32; int radix = 2; int mask = 1; do { buf[--charPos] = digits[value & 1]; value >>>= 1; } while (value != 0); String binaryString = new String(buf, charPos, (32 - charPos)); for (int i = 0; i < binaryString.length(); i++) { char charAt = binaryString.charAt(i); if (charAt == '1') { count++; } } return count; }
相关文章推荐
- Android KitKat 4.4 Wifi移植之Wifi driver
- 【原】相煎何太急——input的blur事件与button的click事件
- [ApiDemos] AlertDialog 使用和源码分析
- Citrix Storefront3.01Web界面自定义修改
- mac配置adb
- 将一个字符串复制到另一个字符串(用指针)
- CSS3阴影 box-shadow的使用和技巧总结
- java导出excel表
- SqlServer2008R几种服务的区别
- 数值的整数次方
- -----------什么是图?------------
- Android 平台语言对照表
- poi操作Excel
- 在Ubuntu上下载Android最新源代码
- CodeForces 589F Gourmet and Banquet 题解
- 如何将一个map 转换成json数据
- 图像特征
- c++ stl容器vector删除(erase),遍历等基本用法介绍及头文件
- JVM中的类加载原理
- LightOJ 1238 Power Puff Girls(BFS)