位运算

 1 // 位操作
 2 // Page77
 3 // 二进制中1的个数
 4 /************
 5 1.n & 1结果为1,则说明最右边的数为1;统计完 n右移一位,考虑下一位是否为1;
 6 2.常规解法,每次循环把与n做与运算的1左移一位,不需要去改变原数n;
 7 3.(n-1)&n的结果是把n的最右边的1变为0
 8 ===========
 9 1循环次数是n中1的个数
10 2循环次数是整数二进制的位数,32为整数需要循环32次
11 3循环次数等于整数中1的个数
12 *************/
13 #include <iostream>
14 using namespace std;
15 
16 void Solution1(int n){
17     int cnt = 0;
18     int cycle = 0;
19     while (n){
20         if (n & 1)
21             cnt++;
22         n = n >> 1; // 缺点:当n为一个负数 0x80000000,右移最高位补1,最终会变成0xFFFFFFFF陷入死循环
23         cycle++;
24 
25     }
26     //return cnt;
27     cout << "Number of 1:" << cnt << endl;
28     cout << "Number of cycle:" << cycle << endl;
29 }
30 
31 int Solution2(int n){
32     int cnt = 0;
33     unsigned int flag = 1;
34     int cycle = 0;
35     while (flag){
36         if (n & flag)
37             cnt++;
38         flag = flag << 1;
39         cycle++;
40     }
41     //return cnt;
42     cout << "Number of 1:" << cnt << endl;
43     cout << "Number of cycle:" << cycle << endl;
44 }
45 
46 int Solution3(int n){
47     int cnt = 0;
48     int cycle = 0;
49     while (n){
50         cnt++;
51         n = (n - 1) & n;
52         cycle++;
53     }
54     cout << "Number of 1:" << cnt << endl;
55     cout << "Number of cycle:" << cycle << endl;
56 }
57 
58 
59 int main(){
60     unsigned int x = 0x7FFFFFFF;
61     //int y = 0x80000000;
62     int y = 0xFFFFFFFF;
63     int z = 0;
64     Solution1(z);
65     Solution2(z);
66     Solution3(z);
67     return 0;
68 
69 }

leetcode中一道关于倒置位的题reverse bits

 1 /********************************
 2 Reverse bits of a given 32 bits unsigned integer.
 3 
 4 For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), 
return 964176192 (represented in binary as 00111001011110000010100101000000).
5 **********************************/ 6 class Solution { 7 public: 8 uint32_t reverseBits(uint32_t n) { 9 uint32_t result = 0; 10 for (int i = 0; i < 32; i++){ 11 result = (result << 1) + ((n >> i) & 1); 12 } 13 return result; 14 } 15 };
原文地址:https://www.cnblogs.com/cnblogsnearby/p/4605846.html