-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbit_calc.cpp
More file actions
66 lines (60 loc) · 986 Bytes
/
bit_calc.cpp
File metadata and controls
66 lines (60 loc) · 986 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
using namespace std;
//计算x有多少个二进制位
int countBits(int x)
{
int ans = 0;
while(x)
{
x/=2;
ans++;
}
return ans;
}
//打印二进制
void printBit(int x)
{
vector<int> ans;
while(x)
{
ans.push_back(x%2);
x/=2;
}
for(auto it = ans.rbegin(); it!=ans.rend() ; it++)
{
cout << *it;
}
cout << endl;
}
bool isPalindrome(int x)
{
vector<int> ans;
while(x)
{
ans.push_back(x%2);
x/=2;
}
auto it1=ans.begin();
auto it2=ans.rbegin();
for(; it1!=ans.end();it1++,it2++)
{
if(*it1!=*it2)
{
return false;
}
}
return true;
}
int main()
{
for(int i=1 ;i<33;i++)
{
int n = i;
cout << "n = " << n << ":";
cout << countBits(n) << endl;
cout << isPalindrome(n) << endl;
printBit(n);
}
return 0;
}