华为OD机考题(HJ62 查找输入整数二进制中1的个数)

前言

经过前期的数据结构和算法学习,开始以OD机考题作为练习题,继续加强下熟练程度。

描述

输入一个正整数,计算它在二进制下的1的个数。

注意多组输入输出!!!!!!

数据范围: 1≤𝑛≤231−1 1≤n≤231−1

输入描述:

输入一个整数

输出描述:

计算整数二进制中1的个数

示例1

输入:

5

输出:

2

说明:

5的二进制表示是101,有2个1

实现原理与步骤

最简单的可以通过Java自带API实现

实现代码(API)

java 复制代码
public class CountBits {
    public static void main(String[] args) {
        int number = 29; // Example number
        int count = Integer.bitCount(number);
        System.out.println("Number of 1s in binary representation of " + number + " is: " + count);
    }
}

实现代码(逐位检查)

java 复制代码
public class CountBits {
    public static void main(String[] args) {
        int number = 29; // Example number
        int count = countBits(number);
        System.out.println("Number of 1s in binary representation of " + number + " is: " + count);
    }

    public static int countBits(int number) {
        int count = 0;
        while (number != 0) {
            count += number & 1; // Check the least significant bit
            number >>= 1; // Right shift by 1
        }
        return count;
    }
}

实现代码(位清零算法)

java 复制代码
public class CountBits {
    public static void main(String[] args) {
        int number = 29; // Example number
        int count = countBits(number);
        System.out.println("Number of 1s in binary representation of " + number + " is: " + count);
    }

    public static int countBits(int number) {
        int count = 0;
        while (number != 0) {
            number &= (number - 1); // Clear the least significant bit set
            count++;
        }
        return count;
    }
}

实现代码(递归算法)

java 复制代码
public class CountBits {
    public static void main(String[] args) {
        int number = 29; // Example number
        int count = countBits(number);
        System.out.println("Number of 1s in binary representation of " + number + " is: " + count);
    }

    public static int countBits(int number) {
        if (number == 0) {
            return 0;
        } else {
            return (number & 1) + countBits(number >> 1);
        }
    }
}
相关推荐
uesowys2 天前
华为OD算法开发指导-任务规划
华为od·算法开发指导
Tony_yitao8 天前
9.华为OD机试真题 - 最长的顺子 - 2024E卷 Java
java·华为od·algorithm
uesowys18 天前
华为OD算法开发指导-简易内存池
java·算法·华为od
闭着眼睛学算法18 天前
【双机位A卷】华为OD笔试之【哈希表】双机位A-采购订单【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·华为od·散列表
闭着眼睛学算法22 天前
【双机位A卷】华为OD笔试之【排序】双机位A-银行插队【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·javascript·c++·python·算法·华为od
uesowys1 个月前
华为OD算法开发指导-比赛的冠亚季军
算法·华为od
我是华为OD~HR~栗栗呀1 个月前
华为od-22届考研-C++面经
java·前端·c++·python·华为od·华为·面试
m0_748240251 个月前
华为OD机考:计算正方形数量(Python & C/C++ & JAVA & JS & GO)
c语言·python·华为od
我是华为OD~HR~栗栗呀1 个月前
华为OD, 测试面经
java·c++·python·华为od·华为·面试
我是华为OD~HR~栗栗呀1 个月前
华为OD-23届-测试面经
java·前端·c++·python·华为od·华为·面试