You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
1.0 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
//https://www.cnblogs.com/littlehb/p/15005256.html
//输出数字n的二进制
int main() {
int n;
n = 1;
//方法1固定1右移n大法
//优点:思路清晰,模板利用扩展
//缺点:代码有点长
for (int i = 7; i >= 0; i--)//这里写7~0是为了少一些前导0看着方便注意从大到小才能正确显示
cout << ((n >> i) & 1); //思路右移i位再&1就知道这个位置是0还是1输出即可
cout << endl;
//方法2固定n左移1大法
//优点:思路清晰,模板利用扩展
//缺点:代码有点长
for (int i = 7; i >= 0; i--)//这里写7~0是为了少一些前导0看着方便,注意从大到小,才能正确显示
if (n & (1 << i)) cout << 1; else cout << 0;
cout << endl;
//方法3内置函数bitset大法
//优点:代码极短
//缺点:没法扩展
cout << bitset<8>(n) << endl;
return 0;
}