Rya*_*anL -1 c++ bit-manipulation
我正在编写一个汉明权重计算器,但为什么数字 3 对于 uint32_t 来说太大了?
编写一个函数,它接受一个无符号整数并返回它所具有的“1”位的数量(也称为汉明权重)。
笔记:
请注意,在某些语言(例如 Java)中,没有无符号整数类型。在这种情况下,输入将以有符号整数类型给出。它不应该影响您的实现,因为整数的内部二进制表示形式是相同的,无论是有符号的还是无符号的。
在 Java 中,编译器使用 2 的补码表示法来表示有符号整数。因此,在示例 3 中,输入表示有符号整数。-3。
// package LeetCode Problem.Problem 2;
// Write a function that takes an unsigned integer and returns the number of '1'
// bits it has (also known as the Hamming weight).
#include <iostream>
using namespace std;
int hammingWeight(uint32_t n);
class BitShifting {
public:
uint32_t n;
int hammingWeight(uint32_t n);
void setn(uint32_t n);
};
void BitShifting::setn(uint32_t n) {
n = n;
}
int BitShifting::hammingWeight(uint32_t n) {
int count = 0;
while (n) { // while n > 0
count += n & 1; // n&1 is a bit comparison for binary ends; returns 0 or 1
// that if true would += 1;
n = n >> 1; // Shift n to the right for one bit
}
return count;
}
int main() {
BitShifting n1, n2, n3;
n1.n = 00000000000000000000000000001011;
n2.n = 00000000000000000000000010000000;
n3.n = 11111111111111111111111111111101;
cout << endl
<< "The hamming weight of Input 1 is: " << n1.hammingWeight(n1.n) << endl
<< "The hamming weight of Input 2 is: " << n2.hammingWeight(n2.n) << endl
<< "The hamming weight of Input 3 is: " << n3.hammingWeight(n3.n);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要以二进制格式输入文字,您需要有前缀0b,如0b11111111111111111111111111111101。
作为比较,0是八进制数的前缀(011 甚至不是十进制的 11,而是十进制的 9),0x是十六进制数的前缀。
| 归档时间: |
|
| 查看次数: |
207 次 |
| 最近记录: |