【LeetCode从零单排】No 191.Number of 1 Bits(考察位运算)
来源:互联网 发布:网络报价单 编辑:程序博客网 时间:2024/06/07 06:16
题目
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
代码
1.递归运算,虽然leet不通过,因为时间原因
public class Solution { // you need to treat n as an unsigned value public static int hammingWeight(int n) { if(n==0) return 0; if(n==1) return 1; int total=1; int index=1; while(n-total*2>=0){ total=total*2; } n=n-total; index=index+hammingWeight(n); return index; }
2.用位运算方法
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { if(n==0) return 0; int i=0; while(n!=0){ n=n & (n-1); i++; } return i; }}
代码下载:https://github.com/jimenbian/GarvinLeetCode
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/
0 0
- 【LeetCode从零单排】No 191.Number of 1 Bits(考察位运算)
- Leetcode#191. Number of 1 Bits(位运算)
- 【LeetCode从零单排】No.9 Palindrome Number
- 【leetcode】191. Number of 1 Bits 关于位运算的几个小技巧。191. Number of 1 Bits()
- Leetcode Number of 1 Bits(位运算)
- LeetCode 191 Number of 1 Bits (位运算)
- Leetcode NO.191 Number of 1 Bits
- 【LeetCode从零单排】No.160 Intersection of Two Linked Lists
- 【LeetCode从零单刷】Number of 1 Bits & Power of Two
- 191. Number of 1 Bits Leetcode Python
- 【LeetCode】191.Number of 1 Bits
- [LeetCode]191.Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- [leetcode] 191. Number of 1 Bits
- <LeetCode OJ> 191. Number of 1 Bits
- Leetcode 191. Number of 1 Bits
- leetCode 191. Number of 1 Bits
- 看好你的门-XSS攻击(1)-利用反射型XSS漏洞 山寨红客插红旗
- HttpURLConnection用法详解
- JVM原理和优化
- hadoop2.x常用端口、定义方法及默认端口、hadoop1.X端口对比
- bitmp 保存到文件中
- 【LeetCode从零单排】No 191.Number of 1 Bits(考察位运算)
- svn新建/删除分支
- 雷达Raid电热蚊香液套装使用方法、注意事项等
- javascript包装对象
- 【LeetCode】Largest Number 解题报告
- Jquery ajax异步请求带来的问题及解决方案
- 把1分解为若干个互不相同的单位分数之和
- iOS应用程序生命周期(前后台切换,应用的各种状态)详解
- Oracle基本数据类型存储格式浅析(一)——字符类型