Files
python/TangDou/AcWing/Bitwise.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

78 lines
2.9 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
//整数转二进制
string IntToBit(int x) {
string s = bitset<32>(x).to_string(), s2;
int i = 0, len = s.length();
while (s[i] == '0') i++;
while (i <= len) s2 += s[i], i++;
return s2;
}
//二进制字符串转整数
int BitStrToInt(string str) {
string bitval5(str);
bitset<32> b5(bitval5);
return b5.to_ulong();
}
int main() {
int x = BitStrToInt("101101");
printf("1.去掉最后一位: 例:(101101->10110) %s\n", IntToBit((x >> 1)).c_str());
printf("2.在最后加一个0 例:(101101->1011010) %s\n", IntToBit((x << 1)).c_str());
printf("3.在最后加一个1 例:(101101->1011011) %s\n", IntToBit((x << 1) + 1).c_str());
x = BitStrToInt("101100");
printf("4.把最后一位变成1 例:(101100->101101) %s\n", IntToBit(x | 1).c_str());
x = BitStrToInt("101101");
printf("5.把最后一位变成0 例:(101101->101100) %s\n", IntToBit((x | 1) - 1).c_str());
printf("6.把最后一位取反: 例:(101101->101100) %s\n", IntToBit((x ^ 1)).c_str());
int k = 3;
x = BitStrToInt("101001");
printf("7.把右数第k位变成1(101001->101101,k=3) %s\n", IntToBit((x | (1 << (k - 1)))).c_str());
x = BitStrToInt("101001");
printf("8.把右数第k位变成0(101001->101001,k=3) %s\n", IntToBit((x & ~(1 << (k - 1)))).c_str());
x = BitStrToInt("101001");
printf("9.把右数第k位取反(101001->101101,k=3) %s\n", IntToBit((x ^ (1 << (k - 1)))).c_str());
x = BitStrToInt("1101101");
printf("10.取末三位:例:(1101101->101) %s\n", IntToBit(x & 7).c_str());
x = BitStrToInt("1101101");
k = 4;
printf("11.取右数第k位(1101101->1,k=4) %s\n", IntToBit(x >> (k - 1) & 1).c_str());
x = BitStrToInt("101001");
k = 4;
printf("12.把末k位变成1(101001->101111,k=4) %s\n", IntToBit(x | ((1 << k) - 1)).c_str());
x = BitStrToInt("101001");
k = 4;
printf("13.把末k位取反(101001->100110,k=4) %s\n", IntToBit(x ^ ((1 << k) - 1)).c_str());
x = BitStrToInt("100101111");
printf("14.把右边连续的1变成0(100101111->100100000) %s\n", IntToBit(x & (x + 1)).c_str());
x = BitStrToInt("100101111");
printf("15.把右起第一个0变成1(100101111->100111111) %s\n", IntToBit(x | (x + 1)).c_str());
x = BitStrToInt("100101111");
printf("16.把右边连续的0变成1(11011000->11011111) %s\n", IntToBit(x | (x - 1)).c_str());
x = BitStrToInt("100101111");
printf("17.取右边连续的1(100101111->1111) %s\n", IntToBit((x ^ (x + 1)) >> 1).c_str());
x = BitStrToInt("100101000");
printf("18.去掉右起第一个1的左边(100101000->1000) %s\n", IntToBit(x & (x ^ (x - 1))).c_str());
return 0;
}