华为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);
        }
    }
}
相关推荐
西电研梦4 天前
26西电考研 | 寒假开始,机试 or C语言程序设计怎么准备?
c语言·考研·华为od·研究生·西安电子科技大学·计算机408
无限码力5 天前
华为OD技术面真题 - Mysql相关 - 4
mysql·华为od·华为od技术面真题·华为od技术面八股·华为od技术面八股文·华为od技术面mysql相关
无限码力5 天前
华为OD机试双机位C卷 - FLASH坏块监测系统 (C语言 & C++ & Python & JAVA & JS & GO)
华为od·华为od机试真题·华为od机试双机位c卷·华为od上机考试双机位c卷·华为od上机考试真题·华为od机考真题·华为odflash坏块监测系统
无限码力5 天前
华为OD技术面真题 - 计算机网络相关 - 4
计算机网络·华为od·华为od技术面真题·华为od技术面计算机八股·华为od技术面计算机网络真题
想七想八不如114086 天前
2019机试真题
java·华为od·华为
开开心心_Every9 天前
家常菜谱软件推荐:分类齐全无广告步骤详细
linux·运维·服务器·华为od·edge·pdf·华为云
无限码力9 天前
华为OD2026最新机试双机位C卷机考真题目录含考点说明 (持续更新)
华为od·华为od机考·华为od题库·华为od机试·华为od机试双机位c卷·华为od最新上机考试题库·od机考题库
无限码力10 天前
华为OD技术面真题 - 数据库MySQL - 3
数据库·mysql·华为od·八股文·华为od技术面八股文
无限码力10 天前
华为OD技术面真题 - JAVA开发 - 5
java·华为od·面试·华为od技术面真题·华为od技术面八股·华为od技术面java八股文