美文网首页剑指offer
二进制中1的个数

二进制中1的个数

作者: G_uest | 来源:发表于2019-07-25 23:30 被阅读0次

题目来源:牛客网--二进制中1的个数

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

解题思路

使用java中内置的函数比较简单,会自动转换为二进制并返回一个字符串,之后只需要遍历字符串中 1 的个数就好了,或者把字符串中的0替换为空字符,对字符串求长。

java代码

import java.util.Scanner;

public class numberOfOne {

    public static void main(String[] args) {
        int count = 0;
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        // 转换为二进制,返回值为字符串
        String str = Integer.toBinaryString(n);
        
        // 把 0 替换成空值,求长度,得到 1 的个数
        // System.out.println(str.replaceAll("0", "").length());
        
        // 遍历字符串,统计 1 的个数
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '1') {
                count++;
            }
        }
        System.out.println(count);
    }
}

调用api属于耍赖?好吧,补上两种不耍赖的
这两种解法题目评论下边都有,翻了一下觉得挺好。

第一种

public static void test(int n) {
    int count = 0;
    while (n !=0) {
        count++;
        // 每次与运算都会把 n 最右边的 1 与掉,这样有多少 1 就循环多少次
        // 1001 & 1000 值为 1000,最右边的 1 掉了
        n = n & (n-1);
    }
    System.out.println(count);
}

第二种

public static void test2(int n) {
    int count = 0;
    while(n != 0) {
        count += n & 1;
        // 无符号右移,这样就不用考虑负数自动补1了,有多少位循环多少次
        // 1001 >>> 1 值为 100
        n = n >>> 1;
    }
    System.out.println(count);
}

相关文章

网友评论

    本文标题:二进制中1的个数

    本文链接:https://www.haomeiwen.com/subject/igklrctx.html