首页 > 其他 > 详细

Count 1 in Binary

时间:2021-04-11 15:50:29      阅读:10      评论:0      收藏:0      [点我收藏+]

Source

Count how many 1 in binary representation of a 32-bit integer.

Example
Given 32, return 1

Given 5, return 2

Given 1023, return 9

Challenge
If the integer is n bits with m 1 bits. Can you do it in O(m) time?

 

题解

题 O1 Check Power of 2 的进阶版,x & (x - 1) 的含义为去掉二进制数中最后一的1,无论 x 是正数还是负数都成立。

Java

public class Solution {
    /**
     * @param num: an integer
     * @return: an integer, the number of ones in num
     */
    public int countOnes(int num) {
        int count = 0;
        while (num != 0) {
            num = num & (num - 1);
            count++;
        }

        return count;
    }
}

源码分析

累加计数器即可。

复杂度分析

这种算法依赖于数中1的个数,时间复杂度为 O(m). 空间复杂度 O(1).

 

Count 1 in Binary

原文:https://www.cnblogs.com/lyc94620/p/14643412.html

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