首页 > 试题广场 >

二进制中有多少个1

[编程题]二进制中有多少个1
  • 热度指数:6848 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
把一个 32-bit 整型转成二进制,其中包含多少个 1 ,比如 5 的二进制表达是 101 ,其中包含 2 个 1
 
数据范围:输入的数字满足

输入描述:
输入为整型(十进制),只需兼容32-bit即可,如5、32


输出描述:
输出为字符串,如“2”、“1”
示例1

输入

5

输出

2

说明

5的二进制是101,其中包含2个1 
示例2

输入

0

输出

0
Java解答:
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int sum = 0;
        while(n != 0){
            sum = sum + n%2;
            n = n / 2;
        }
        System.out.println(sum);
    }
}

发表于 2019-08-02 20:18:50 回复(0)
#include <iostream>
using namespace std;
int main()
{
    int x ;
    cin >> x;
    int temp = 0;
    while(x)
    {
        if(x%2!=0)
           temp++;
        x = x/2;
    }
    cout << temp << endl;
    return 0;
}

发表于 2019-11-01 16:17:10 回复(0)
n = int(input().strip())
print(str(bin(n)).count("1"))

发表于 2019-07-31 21:43:57 回复(3)

为什么要做的那么麻烦呢
直接用lowbit函数不就好了?

#include <bits/stdc++.h>
using namespace std;
int n;
int main() {    
    cin >> n;
    bitset<32>a(n);
    printf("%d\n", a.count());
}
发表于 2019-07-20 08:03:33 回复(0)
#include <stdio.h>
#include <stdlib.h>

int bit_count(int x) {
  int n = 0;
  while (x) {
    x &= x - 1;
    ++n;
  }
  return n;
}

int main(const int argc, const char* const argv[]) {
  int x;
  fscanf(stdin, "%d", &x);
  fprintf(stdout, "%d\n", bit_count(x));
  return 0;

发表于 2021-08-05 18:54:10 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt();

        String s = Integer.toBinaryString(i);
        char[] array = s.toCharArray();
        int count=0;
        for (char c : array) {
            if (c=='1')
                count++;
        }
        System.out.println(count);
    }
}

发表于 2020-02-28 21:05:14 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n = 0;
    while (cin >> n) {
        bitset<32> b(n);
        cout << b.count() << endl;
    }
    return 0;
}

发表于 2019-10-17 11:43:28 回复(0)
简单位运算就好
#include<stdio.h>

int main()
{
    int n;
    scanf("%d",&n);
    int ans = 0;
    while(n){
        if(n & 1){
            ans++;
        }
        n >>= 1;
    }
    printf("%d",ans);
    return 0;
}

发表于 2019-10-04 15:07:38 回复(1)
n = int(input())
res = 0
while n > 0:
    if n % 2 == 1: # 遇到奇数则表明该位为1
        res += 1
    n = n // 2
print(res)
ez
发表于 2019-09-09 13:37:01 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main(){
    int n, cnt=0;
    cin>>n;
    while(n){
        if(n&1)
            cnt++;
        n>>=1;
    }
    cout<<cnt<<endl;
    return 0;
}

发表于 2019-08-30 01:04:21 回复(0)
s = int(input())
count = 0
if s <2:
    print(s)
else:
    while s >0:
        if s % 2 == 1:
            count += 1
        s = s//2
    print(count)

发表于 2019-06-27 09:14:10 回复(0)
python一行足矣
print(bin(int(input())).count('1'))


发表于 2019-12-03 11:05:08 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int res=0,n;
    cin>>n;
    while(n)
    {
        if(n%2==1)
            res++;
        n/=2;
    }
    cout<<res<<endl;
    return 0;
}

发表于 2019-07-13 19:14:21 回复(0)
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    // Write your code here
    line = await readline()
    let tokens = line*1
    let str=tokens.toString(2)
    console.log(str.match(/1/g)?.length||0)
}()

发表于 2024-01-05 11:17:07 回复(0)
package main

import (
    "fmt"
)

func main() {
    var x int
    fmt.Scan(&x)
    cnt:=0
    for x>0{
        cnt+=x%2
        x/=2
    }
    fmt.Print(cnt)
}

发表于 2023-03-18 11:38:08 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int digit = Integer.valueOf(sc.nextLine());
        
        int num = getNumOfOne(digit);
        System.out.println(num);
    }
    
    public static int getNumOfOne(int digit) {
        int num = 0;
        for (int i = 0; i < 32; i++) {
            //例:10011011
            // 每次右移一位,判断是否为1
            num += digit & 1;
            digit >>>= 1;
        }
        
        return num;
    }
}

发表于 2022-08-30 08:43:41 回复(0)
发表于 2021-08-03 18:58:49 回复(0)
"""
利用位运算符求解
"""
n = int(input())
c = 0
while n:
    n &= (n-1) # 消去n的二进制表达中最后一个1
    c += 1
print(str(c))

发表于 2021-07-14 15:08:34 回复(0)
#include<iostream>
using namespace std;
int main()
{
    int num;
    cin>>num;
    int count=0;
    while(num)
    {
        if(num%2!=0)
            count++;
        num/=2;
    }
    cout<<count<<endl;
    system("pause");
    return 0;
}
发表于 2020-08-24 21:50:24 回复(0)
import java.util.Scanner;
public class Main {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int num = in.nextInt();
            /*
             * 将输入的数num与1做&运算,这样会取到num二进制的
             * 的最后一位(0或1),之后将num右移一位,与1做&运算后会取到num的第二位
             * 依次类推就能得出num每一位上的1
             *
             * eg:
             * 101 & 001 = 001 count == 0 + 1
             * 101 >>> 1 = 010
             * 010 & 001 = 000 count == 1 + 0
             * 010 >>> 1 = 001
             * 001 & 001 = 001 count == 1 + 1
             * 
             */
            int count = 0;
            while (num > 0) {
                count += num & 1;
                num = num >>> 1;
            }
            System.out.print(count);
        }
}


编辑于 2020-06-29 09:10:48 回复(0)