【LeetCode191】Number of 1 Bits★

1.题目

2.思路

 

方法一:常规方法。

 

方法二:给面试官惊喜的解法。

 

3.java代码

 方法一代码:

 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         int count=0;
 5     int flag=1;
 6     while(flag!=0){
 7         if((n&flag)!=0)
 8             count++;
 9         flag=flag<<1;
10         }
11     return count;
12     }
13 }

 方法二代码:

 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         int count=0;
 5         while(n!=0){
 6             count++;
 7             n=n&(n-1);
 8         }
 9         return count;
10     }
11 }
posted @ 2017-03-16 11:43  追梦boy  阅读(152)  评论(0编辑  收藏  举报