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

LeetCode 191. Number of 1 Bits QuestionEditorial Solution

时间:2016-09-24 10:40:34      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

题意:给你一个整数,计算该整数的二进制形式里有多少个“1”。比如6(110),就有2个“1”。

 

一开始我就把数字n不断右移,然后判定最右位是否为1,是就cnt++,否则就继续右移直到n为0。

可是题目说了是无符号整数,所以给了2147483648,就WA了。

因为java里的int默认当做有符号数来操作的,而2147483648超过int的最大整数,所以在int里面其实是当做-1来计算的。

那么,不能再while里面判断n是否大于0,和使用位操作符>>。应该使用位操作符>>>,这个操作符是对无符号数进行右移的。

 

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int cnt = 0;
        for(int i = 0; i < 32; i++) {
            if( ((n>>>i)&1) == 1 ) cnt++;
        }
        return cnt;
    }
}

 

LeetCode 191. Number of 1 Bits QuestionEditorial Solution

标签:

原文地址:http://www.cnblogs.com/sevenun/p/5902477.html

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