LeetCode-探索-初级算法-其他-1. 位1的个数(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-其他-1. 位1的个数(个人做题记录,不是习题讲解)

LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/

  1. 位1的个数
  • 语言:java

  • 思路:用位运算来比较是否为1,然后记录1的数量

  • 代码(1ms):

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int res = 0;
            for(int i = 0; i < 32; ++i){
                res += n & 1;
                n >>>= 1 ;
            }
            return res;
        }
    }
    
  • 参考代码(0ms):也是从右往左判断1的数量,不过比我的更加巧妙,n & (n-1),算后面的计算利用到了前面的计算,有动态规划的感觉。

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            while(n!=0){
                ++count;
                n &= (n-1);
            }
            return count;
        }
    }
    
发布了60 篇原创文章 · 获赞 6 · 访问量 5517

猜你喜欢

转载自blog.csdn.net/Ashiamd/article/details/102729176