题解 | #矩形覆盖#

二进制中1的个数

http://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8

注意 不能用本身的数去右移 因为如果是负数的话 右移补的是1 而我们恰恰要求的是1的个数
方法1 用1开始往左移一次位与 如果不为0说明当前位是1 count++

class Solution1 {
    public int NumberOf1(int n) {
        int count=0;
        int flag=1;
        while (flag!=0){
            if ((flag&n)!=0){
                count++;
            }
            flag=flag<<1;
        }
        return count;
    }
}

方法2 巧妙 如果当前n>0 说明至少有一个n 那么我先count++ n-1这个操作是吧当前的1给消除了(n-1)&n 是吧消除当前1所带来的不必要的1给消除了 n=(n-1)&n;此时的n就是消除了当前1的n

class Solution {
    public int NumberOf1(int n) {
        int count=0;
        while (n!=0){
            count++;
            n=(n-1)&n;
        }
        return count;
    }
}
全部评论

相关推荐

10-10 16:30
济宁学院 Java
不想做程序员:面试官:蓝桥杯三等奖?你多去两次厕所都能拿二等吧
点赞 评论 收藏
分享
09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务