用位運算實現十進制轉換為二進制


代碼如下:

 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 }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM