返回

求整数内存1的个数

前端

一、问题背景

在计算机科学中,我们经常需要处理各种各样的数据,而整数是其中一种最常见的类型。当我们把一个整数存储在计算机内存中时,它会以二进制的形式进行存储,因此,整数在内存中存储时 1 的个数是一个很有趣的问题。

二、解决思路

为了求出整数在内存中存储时 1 的个数,我们可以采用以下步骤:

  1. 把整数转换为二进制形式。
  2. 统计二进制形式中 1 的个数。

三、具体实现

接下来,我们将使用 C 语言、Java 和 Python 来实现这个算法。

1. C 语言

#include <stdio.h>

int count_ones(int n) {
    int count = 0;
    while (n) {
        if (n & 1) {
            count++;
        }
        n >>= 1;
    }
    return count;
}

int main() {
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);

    int count = count_ones(n);
    printf("The number of 1's in the binary representation of %d is %d\n", n, count);

    return 0;
}

2. Java

import java.util.Scanner;

public class CountOnes {

    public static int countOnes(int n) {
        int count = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                count++;
            }
            n >>>= 1;
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = scanner.nextInt();

        int count = countOnes(n);
        System.out.println("The number of 1's in the binary representation of " + n + " is " + count);
    }
}

3. Python

def count_ones(n):
    count = 0
    while n:
        if n & 1:
            count += 1
        n >>= 1
    return count

if __name__ == "__main__":
    n = int(input("Enter an integer: "))
    count = count_ones(n)
    print("The number of 1's in the binary representation of", n, "is", count)

四、算法分析

这个算法的时间复杂度为 O(log n),因为我们需要遍历整数的二进制位,而二进制位的数量与整数的位数成正比。在最坏的情况下,当整数为 2^31-1 时,算法需要遍历 32 个二进制位,因此时间复杂度为 O(log n)。

五、结语

在本文中,我们介绍了如何求出整数在内存中存储时 1 的个数,并提供了 C 语言、Java 和 Python 的示例代码。希望您能通过本文对该算法有一个更深入的理解。