Leetcode#191Number of 1 Bits

时间:2015-04-28 18:55:20   收藏:0   阅读:252

public class Solution {

    // you need to treat n as an unsigned value

    public int hammingWeight(int n) {

        int c=0;

        while(n>0)

        {

            c=c+n%2;

            n=n/2;

        }

        if(n==1)

            return c+1;

        else

            return c;

    }

}



Input:2147483648 (10000000000000000000000000000000)
Output:0
Expected:1

原因,题目要求int是无符号int型,而java中int是由符号的,因此当输入2147483648时为0而其表示是10000。。。000所以采用二进制的&运算,如下


public class Solution {

    // you need to treat n as an unsigned value

    public int hammingWeight(int n) {

        int s=0;

        while(n!=0)

        {

            s++;

            n=n&(n-1);

        }

        return s;

    }

}



原文:http://7061299.blog.51cto.com/7051299/1639719

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!