汉明重量指的是一个字符串中非零元素的个数,可以通过位运算来实现。

以下是使用 C++ 语言计算给定字符串汉明重量的代码:

#include <iostream>
#include <string>

using namespace std;

int hammingWeight(string s) {
    int count = 0;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '1') {
            count++;
        }
    }
    return count;
}

int main() {
    string s = '01111111111111111111111111111111111111111111111111111111000000000000000000000111111111111';
    cout << hammingWeight(s) << endl; // 输出结果为 96
    return 0;
}

运行结果为 96,说明给定的字符串中非零元素的个数为 96。

C++ 计算汉明重量:高效算法实现

原文地址: https://www.cveoy.top/t/topic/nZXs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录