Number of 1 Bits

第一次在leetcode上刷题,居然会紧张。。。其实这道题去年8月份就在《编程之美》上遇到过,当时自己用的对2求余数的方法,答案提供了一个移位的方法,也都做过笔记,没想到隔了半年再练手的时候这么生疏,明明知道大概是个怎样的思路,但是一敲出来就各种错误,也是醉了。所以说,算法题只是做过是没用的,做过两三遍也是没用的,关键是能做到每一次做都能快速并且准确无误地做出来。

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

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

下面是leetcode里vote最多的一个解题方法,大概思路也差不多,就是少用了一个变量,而且用到了>>>运算符,说实话在这之前我都不知道这个符号的意思,我单纯地想着把n>>>=1替换成n = n >>1效果也一样,但是运行之后会提示"Time Limit Exceeded"错误,后来查过才知道原来>>>是无符号右移的意思,涨姿势了。

</pre><pre name="code" class="java">public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int result = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                result++;
            }
            n >>>= 1;
        }
        return result;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值