华为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);
        }
    }
}
相关推荐
哪 吒1 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
蜗牛的旷野12 天前
华为OD机试_2025 B卷_矩形相交的面积(Python,100分)(附详细解题思路)
开发语言·python·华为od
_不会dp不改名_13 天前
华为OD 最小循环子数组
算法·华为od·kmp
m0_6407435613 天前
华为OD-2024年E卷-字符串化繁为简[200分] -- python
python·华为od
小猫咪怎么会有坏心思呢13 天前
华为OD机考-生成哈夫曼树-二叉树(JAVA 2025B卷)
java·开发语言·华为od
小猫咪怎么会有坏心思呢14 天前
华为OD机试-云短信平台优惠活动-完全背包(JAVA 2024E卷)
java·开发语言·华为od
小猫咪怎么会有坏心思呢14 天前
华为OD机考-小明减肥-DFS(JAVA 2025B卷)
java·华为od·深度优先
小猫咪怎么会有坏心思呢14 天前
华为OD机考-最小循环子数组-字符串(JAVA 2025B卷)
java·开发语言·华为od
m0_6407435616 天前
华为OD-2024年E卷-中文分词模拟器[200分] -- python
python·华为od·中文分词
小猫咪怎么会有坏心思呢16 天前
华为OD机试-最佳植树距离-二分(JAVA 2025A卷)
java·开发语言·华为od