题解 | #二进制中1的个数#

二进制中1的个数

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

">>>"无符号右移

操作规则:无论正负数,前面补零。

">>"右移

操作规则:正数前面补零,负数前面补1

"<<"左移

操作规则:无论正负数,后面补零。

方法一:位运算

 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int NumberOf1(int n ) {
    // write code here
    int flag = 0x0001;
    int i = 0;
    int iNum = 0;
    
    for (i = 0; i < 32; i++)
    {
        iNum += (n & flag);
        n = n >> 1;
    }
    return iNum;
}

方法二:巧用 n & (n−1)

  • (n−1) 解析:二进制数字n最右边的1变成0,此1右边的0都变成1 。
  • n & (n−1) 解析: 二进制数字 nn 最右边的 11 变成 00 ,其余不变。 alt
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int NumberOf1(int n ) {
    // write code here
    int iNum = 0;
    while (n)
    {
        iNum++;
        n = n & (n - 1);
    }
    return iNum;
}

方法二来源: LeetCode K神 链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/solution/mian-shi-ti-15-er-jin-zhi-zhong-1de-ge-shu-wei-yun/

全部评论

相关推荐

01-30 16:13
浙江大学 Java
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

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