首页 > 其他 > 详细

Leetcode#191Number of 1 Bits

时间:2015-04-28 18:55:20      阅读:252      评论:0      收藏:0      [点我收藏+]

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;

    }

}



Leetcode#191Number of 1 Bits

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!