华为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 天前
整数编码 - 华为OD统一考试(A卷、C++)
数据结构·c++·算法·华为od
纪元A梦1 天前
华为OD全流程解析+备考攻略+经验分享
经验分享·华为od
什码情况6 天前
微服务集成测试 -华为OD机试真题(A卷、JavaScript)
javascript·数据结构·算法·华为od·机试
什码情况10 天前
回文时间 - 携程机试真题题解
数据结构·python·算法·华为od·机试
蓝白咖啡11 天前
华为OD机试 - 王者荣耀匹配机制 - 回溯(Java 2024 D卷 200分)
java·python·算法·华为od·机试
郝晨妤17 天前
鸿蒙常见面试题(欢迎投稿一起完善持续更新——已更新到62)
服务器·javascript·华为od·华为·harmonyos·鸿蒙
程序员yt20 天前
西交建筑学本科秋天毕业想转码,自学了Python+408,华为OD社招还是考研更香?
python·考研·华为od
CodeClimb22 天前
【华为OD-E卷 - 单词接龙 100分(python、java、c++、js、c)】
java·javascript·c++·python·华为od
猿六凯23 天前
2024山东大学计算机复试上机真题
华为od
猿六凯25 天前
2024浙江大学计算机考研上机真题
考研·华为od