비트 연산으로 10진법을 2진법으로 변환하다

7693 단어 진수 변환
코드는 다음과 같습니다.
 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의 2진법 형식을 전체적으로 왼쪽으로 j위를 옮기고 왼쪽으로 옮긴 후 낮은 위치에서 0을 보충하며 옮긴 높은 부분은 버려진다는 것을 나타낸다.예를 들어 j가 15일 때 표현식(1<그래서 i&(1<어떤 어린이 신발은mod(취여)연산을 사용하면 효과를 얻을 수 있다고 생각할 수 있지만 비트연산의'개성'은 데이터의 2진법 형식을 직접 조작하는 신속성(일반 컴퓨터의 데이터 저장 기본 형식은 2진법 형식)을 결정한다. 두 개의 같은 알고리즘의 프로그램은 비트연산을 사용하면 프로그램의 속도를 높일 수 있다.
 
 
 
비슷한 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, 즉 2진수 중 0이 아닌 개수를 계산한다.
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 }

 
 
 
LetCode의 두 번째 문제:
 

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 }

 
 

좋은 웹페이지 즐겨찾기