This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
#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;
//方法3:内置函数bitset大法
//优点:代码极短
//缺点:没法扩展
cout << bitset<8>(n) << endl;
return 0;
}