学习目标:
位运算
学习内容:
剑指 Offer 15. 二进制中 1 的个数
右移 >> 除
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while (n != 0) {
res += 1 & n;
n >>= 1;
}
return res;
}
};
剑指 Offer 65. 不用加减乘除做加法
先无进位,再进位
class Solution {
public:
int add(int a, int b) {
while (b != 0) {
int c = (unsigned int)(a & b) << 1;
a ^= b;
b = c;
}
return a;
}
};
啊啊啊啊,田田,不要啊,不要不理我啊 呜呜呜
invert4.c
#include <limits.h>
#include <stdio.h>
char *itobs(int, char *);
void show_bstr(const char *);
int invert_end(int num, int bits);
int main() {
char bin_str[CHAR_BIT * sizeof(int) + 1];
int number;
puts("Enter integers and see them in binary.");
puts("Non-numeric input terminates program.");
while (scanf("%d", &number) == 1) {
itobs(number, bin_str);
printf("%d is \n", number);
show_bstr(bin_str);
putchar('\n');
number = invert_end(number, 4);
printf("Inverting the last 4 bits gives\n");
show_bstr(itobs(number, bin_str));
putchar('\n');
}
puts("Bye!");
return 0;
}
char *itobs(int number, char *bin_str) {
int size = CHAR_BIT * sizeof(int);
int i;
for (i = size - 1; i >= 0; --i, number >>= 1) {
bin_str[i] = (01 & number) + '0';
}
return bin_str;
}
void show_bstr(const char *bin_str) {
int i = 0;
while (bin_str[i]) {
putchar(bin_str[i]);
if (++i % 4 == 0 && bin_str[i])
putchar(' ');
}
}
int invert_end(int num, int bits) {
int mask = 0;
int bitval = 1;
while (bits-- > 0) {
mask |= bitval;
bitval <<= 1;
}
return num ^ mask;
}
|