码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-191. Number of 1 Bits

时间:2016-03-20 17:44:45      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

这道题考察的是一个二进制的特性。通过n&(n-1)可以判断n的二进制表示中有几个1.(最开始超时这道题的时候我心中是万马奔腾的) 

// you need to treat n as an unsigned value

public int hammingWeight(int n) { int count=0;while(n!=0) { count++; n = n & (n - 1); } return count; }

开始我的代码:

public int hammingWeight(int n)
{
    int count=0;
    while(n!=0)
    {
        count+=n&0x1;
        n=n>>1;
    }
    return count;
}

 

LeetCode-191. Number of 1 Bits

标签:

原文地址:http://www.cnblogs.com/ren-jie/p/5298145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!