用位运算实现十进制转换为二进制

代码如下:

 1 #include <iostream>        //将十进制数转化为二进制数,位运算的取位操作
 2 using namespace std;
 3 int main()
 4 {
 5        unsigned short i;
 6        cout << "请输入一个小于65536的正整数" << endl;
 7        cin >> i;
 8        for(int j=15; j >= 0; j--)
 9        {
10               if ( i & ( 1 << j) ) cout << "1";
11               else cout << "0";
12        }
13        cout << endl;
14
15     return 0;
16 }

分析:

      分析一下这个程序的算法原理,顺便复习一下位运算的奇妙吧。

      这是一个将无符号十进制数转化为标准16位二进制数的程序。

      程序的主体部分,for语句从15递减到0,一共16次对二进制数的每一位的判断作操作。循环体内部的条件判断用到了位运算中的&运算(与运算)和<<运算(左移运算)。<<运算表示把1的二进制形式整体向左移j位,左移后低位补0,移出的高位部分被舍弃。例如,当j15时,表达式(1<<j)的值为1000000000000000;当j10时,值为0000010000000000

      所以i&1<<j)的值相当于把i的二进制的第j位取出来(i的第j位与(1<<j)的第j位(由上述可以,为1)作与运算,只有当i的第j位为1时值为真)。循环后既得i的二进制形式。

      有的童鞋可能觉得用mod(取余)运算照样可以达到效果,但是位运算的“个性”就决定了它直接对数据的二进制形式进行操作的快捷性(一般计算机的数据存储基本形式为二进制形式),两个相同算法的程序,用了位运算后会使程序速度上有提高。

 

 

 

类似的 LeetCode 上的第一题 :

 

Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

算整数 n 的 Hamming weight,也就是其二进制位中非零位的个数。

AC代码:

1 int hammingWeight(uint32_t n)  {
2     int i, ans=0;
3     for (i=31; i>=0; i--)
4     {
5         if (n & (1 << i)) ans++;
6     }
7     return ans;
8 }

  LeetCode 上的第二题:

 

Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

AC代码:

 1 uint32_t reverseBits(uint32_t n) {
 2     int i;
 3     uint32_t ans;
 4     
 5     if (n & 1) ans=1;
 6     else ans=0;
 7     for (i=1; i<=31; i++)
 8     {
 9         ans <<= 1;
10         if ((n & (1 << i))) ans |= 1;
11     }
12     
13     return ans;
14 }

 

原文地址:https://www.cnblogs.com/maples7/p/4324844.html